Scenario Requirements
The most recent parsing packet, because the protocol has changed, the original fixed length of the package, now becomes indefinite length. For example, the agreement stipulates that a package, there are 8 tags, but each up, not necessarily have 8, no, hardware comes over is 0. At the same time there is also a field, indicating the number of labels.
So I set up a corresponding class here, there are 8 of the marked Signature section for each label. Therefore, in the resolution, according to the number of tags up, dynamic for each label assigned value.
When reading, it is also a field that reads only a certain number of fields.
So, use reflection processing.
Dynamically assign values (for attributes)
Examples are as follows, assigning values to the corresponding fields according to the number.
Declare the required fields first:
private int tagNum;
private long tag0Addr;
private int tag0Voltage;
private long tag1Addr;
private int tag1Voltage;
private long tag2Addr;
private int tag2Voltage;
private long tag3Addr;
private int tag3Voltage;
private long tag4Addr;
private int tag4Voltage;
private long tag5Addr;
private int tag5Voltage;
private long tag6Addr;
private int tag6Voltage;
private long tag7Addr;
private int tag7Voltage;
Then start the dynamic assignment:
for (int i =0;i<tagNum;i++){
Field fieldAddr = this.getClass().getDeclaredField("tag"+i+"Addr");
fieldAddr.setLong(this,NocHelper.asUnsignedInt(data.getInt()));
Field fieldVol = this.getClass().getDeclaredField("tag"+i+"Voltage");
fieldVol.setInt(this,NocHelper.asUnsignedByte(data.get()));
}
Because it is a private property, you must Getdeclaredfield, or you cannot find the field.
So that they can be assigned a value.
Value (for method)
for (int I = 0; I Span class= "pun" >< Sensortag. I++) {
Method method = sensorTag.getClass().getMethod("getTag" + i + "Addr");
String tagAddr = (String) method.invoke(sensorTag);
//do something for every tag
}
Here is the application of reflection on methods and properties.
Java Reflection Applications