mercredi 23 mai 2018

How to Dynamically call and setter and getter methods using Reflection class?

Say I have class AccountPojo and GetAccountPojo with its stter and getter methods as below.

public class AccountPojo{

    private String dataList;
    private String dataSet;

    public String getDataList() {
        return dataList;
    }

    public void setDataList(String dataList) {
        this.dataList = dataList;
    }

    public String getDataSet() {
        return dataSet;
    }

    public void setDataSet(String dataSet) {
        this.dataSet = dataSet;
    }
} 

public class GetAccountsPojo{

    private String accountId;
    private int noOfAccounts;

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public int getNoOfAccounts() {
        return noOfAccounts;
    }

    public void setNoOfAccounts(int noOfAccounts) {
        this.noOfAccounts = noOfAccounts;
    }
}

Now I have class Test.java as below

public Class Test{

 p.s.v.m{

  Class cls = Class.forName("com.org.temp."+ClassName);// ClassName(AccountPojo/GetAccountPojo) here i know already which class is getting called.

  Object clsInstance = (Object) cls.newInstance();

  System.out.println("The cls is==" + cls+" and classInstance is=="+clsInstance);

// Here i want to access getter and setter methods of AccountPojo and GetAcoountPojo dynamically , no hard coding


}   





Aucun commentaire:

Enregistrer un commentaire