samedi 25 août 2018

How to set values by accessing variable through method invocation

How can I set values to tmpBean of MainAction01 with bean values passed by class Operation in below example:

public class Bean01 {
  private int Id01 = 0;
  //getters and setters
}

public interface MainInterface<T> {
  public T getBean();
}

public class MainActionBase<T> {
  public final void startMainJob(T objBean) throws RuntimeException {
    try {
      Object bean = new Object();
      Method getBean = this.getClass().getDeclaredMethod("getBean");
      getBean.setAccessible(true);
      bean = getBean.invoke(this);
      bean = objBean;
    } catch (Exception ex) {
      Logger.getLogger(MainActionBase.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}

public class MainAction01 extends MainActionBase implements MainInterface<Bean01> {
  private Bean01 tmpBean = new Bean01();

  @Override
  public Bean01 getBean(){
    return tmpBean;
  }

  public void getBeanDetails(){
    System.out.println("Id01: " + tmpBean.getId01());
  }
}

public class Operation {
  public static void main(String[] args) {
    Bean01 tmpBean = new Bean01();
    tmpBean.setId01(100);
    MainAction01 tmpMain = new MainAction01();
    tmpMain.startMainJob(tmpBean);
    tmpMain.getBeanDetails();
  }
}

I cannot access the field tmpBean in MainAction01 since I am not aware what of field name in other classes extending MainActionBase. I can only access bean through getBean() method forced by interface.

I know my method of setting bean = objBean does not make sense and rightly so the values are not set to tmpBean.





Aucun commentaire:

Enregistrer un commentaire