how to Call setter method dynamic using Fields set value?

69 Views Asked by At

In my code i have some class that need to be deliver ( send using UDP ) to some server that the element struct that he receive contain Unsigned32 type values.

I using javolution to define the element struct =>

import javolution.io.Struct;

public class ElementData
{
    public Struct.Unsigned32 data1;
    public Struct.Unsigned32 data2;
    public Struct.Unsigned32 data3;
    public Struct.Unsigned32 data4;
    public Struct.Unsigned32 data5;
    public Struct.Unsigned32 data6;
    public Struct.Unsigned32 data7;
    public Struct.Unsigned32 data8;
}

I wrote code that read the element struct value data from CVS file - and sending the element struct to the server. I want to set the values of the element using the 'Field' reflection - but i can't do it because i can't set the value directly - so i must call the 'set' method of the unsigned32 for doing it

example:

 public static void main(String[] args) throws NoSuchFieldException {
    ElementData element = new ElementData();

    Field[] allFields = ElementData.class.getDeclaredFields();

    Unsigned32 tmp = new Unsigned32();
    tmp.set(12);


    Field f1 = ElementData.class.getDeclaredField(allFields[0].getName());

    f1.setInt(element, 12);         // error because 12 is Int and not Unsigned32
    f1.set(element, 12);              // error also
    f1.set(element, tmp);              // error also

}

I looking for any possible way to call the setter using the Fields

1

There are 1 best solutions below

0
On
public static void main(String[] args) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { //add these throws

ElementData element = new ElementData();

Field[] allFields = ElementData.class.getFields(); //Change to getFields

Field f1 = ElementData.class.getField(allFields[0].getName()); //Change to getField

Unsigned32 tmp = new Unsigned32(); 

tmp.set(12);

f1.set(element, tmp); //let just f1.set

}  

Let us know if it's works.