dimanche 5 mars 2017

Setting private fields using Java Reflection

While using java reflection, Can we set a private field without having to tell the parameter type.

For example, if this is my Child class,

package reflection;

public class Child {

    private String name;
    private Integer value;
    private boolean flag;


    public String getLName()
    {
        return this.name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Integer getValue()
    {
        return this.value;
    }

    public void setValue(Integer value)
    {
        this.value = value;
    }

    public boolean getFlag()
    {
        return this.flag;
    }

    public void setFlag(boolean flag)
    {
        this.flag = flag;
    }

    public String toString()
    {
        return "Name" + this.name;
    }
}

I want to set fields of this Child class in my Tester class.

package reflection;

public class Tester {

    public static void main(String args[]) throws Exception
    {



        Class<?> clazz = Class.forName("reflection.Child");
        Object cc = clazz.newInstance();
        cc.getClass().getMethod("setName", String.class).invoke(cc,"AAA");
    }
}

Here I am setting the value of Name field. In the line,

cc.getClass().getMethod("setName", String.class).invoke(cc,"AAA");

I have used String.class. Is there a way to do this, without having to tell the field type. Can Java automatically identify the type somehow? This is because I will get the name, value and flag data from a csv file, and I want to set all the three fields in a single line using a loop. I will declare an array of String with values - "setName", "setValue" and "setFlag" and then I want to use something of the following

cc.getClass().getMethod(array[index]).invoke(cc,data);

I know the above statement is wrong, but is there some alternative to this?





Aucun commentaire:

Enregistrer un commentaire