Karthigeyan Vellasamy
Karthigeyan Vellasamy

Reputation: 2066

Get bean declared as field - its value using Reflection

My requirement is to get values from my bean and set it to my XML.

Using reflection i got all my method name in Map.. and pass the method name inside myClass.getMethod("getProposerName", new Class[] {}) and get value. My input will be TestBean instance as argument using that instance i have to grab all values

Execute Method

public void executeMethod(Class<?> className)  //where i get instance of TestBean
{
    Class<?>  myClass = Class.forName(className.getName()); ////I pass as argument
    Object instance = myClass.newInstance();
    Method method = myClass.getMethod("Pass my method name", new Class[] {}); //Pass my methodname i.e getProposerName
    String Value= (String) method.invoke(instance , new Object[] {}); // Here i get my proposer name of class 
}

The value of policyname is set as follows

TestBean instance =  new  TestBean();
instance.setProposerName("Jack");
instance.getDeclaredBean.setPolicyName("Accident Policy"); // Note : This is problem how to maintain the reference of TestBean to get accident Policy in above execution method

I have this above piece of code which helps me to get the values from TestBean but my problem is DeclaredBean value which is a field type in TestBean. Help me here using above execution method ..

I have n number of class value to extract using this execution method. Below are my two classes.

TestBean.java

public class TestBean 
{
    private String proposerName;

    public DeclaredBean declaredBean;

    public TestBean() {
        super();
    } 

    public String getProposerName() {
        return proposerName;
    }

    public DeclaredBean getDeclaredBean() {
        return declaredBean;
    }

    public void setDeclaredBean(DeclaredBean declaredBean){
        this.declaredBean = declaredBean;
    }

    public void setProposerName(String proposerName) {
        this.proposerName = proposerName;
    }
}

DeclaredBean.java

public class DeclaredBean 
{
    private String policyName;

    public DeclaredBean() {
        super();
    }

    public String getPolicyName() {
        return policyName;
    }

    public void setPolicyName(String policyName) { // Access this method in my execute method
        this.policyName = policyName;  
    }   
}

Upvotes: 1

Views: 1177

Answers (1)

Gerardo Lastra
Gerardo Lastra

Reputation: 665

The question itself is confusing as hell, but I guess (and by guess I really mean guess) you are trying to get the value of a field in an object without actually knowing how to access it. In such case, take a look at Apache Commons BeanUtils (especially the BeanUtils.get*Property() methods).

On the other hand, if what you need is just to serialize objects into XML, you should look into APIs that help you with this (JAXB for example) instead of writing your own code.

Upvotes: 1

Related Questions