lundi 17 avril 2017

How to access getter method of bean class using reflection api?

Why the value is null for the variable2 , if I instantiate the class using Reflection API ? where,the value of Variable1 is returned correctly as per the set and here I instantiated the object normally. How can I obtain the value of variable2 using ReflectionAPI ?

package com.OP.app;

public class Bean {

private String variable1;
private String variable2;
public String getVariable1() {
    return variable1;
}
public void setVariable1(String variable1) {
    this.variable1 = variable1;
}
public String getVariable2() {
    return variable2;
}
public void setVariable2(String variable2) {
    this.variable2 = variable2;
}

}

package com.OP.app;

import java.lang.reflect.Method;

public class ObjectCall {

public static void main(String []args){
    Bean beanobject = new Bean();
    beanobject.setVariable1("Ram");
    beanobject.setVariable2("Rakesh");
    System.out.println(beanobject.getVariable1());
    String path = "com.OP.app.Bean";
    Class<?> newClass;
    try {
        newClass = Class.forName(path);
        Object obj = newClass.newInstance();
         String getMethod = "getVariable2";
         Method getNameMethod = obj.getClass().getMethod(getMethod);
         String name = (String) getNameMethod.invoke(obj); 
         System.out.println(name);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // convert string classname to class
}

}

Output : Ram null





Aucun commentaire:

Enregistrer un commentaire