mardi 3 mars 2020

Java reflection, build an object extending an abstract class

Here is my class definition :

public class MyClass extends MySuperAbstractClass {
   @Column(name="ID")
   private String Id;
   ...
}

public abstract class MySuperAbstractClass  {
  @Column(name="columnName")
  private String columnName;

...
}

In the method using the java reflection the IN argument is the Class of the Object I want to create. (here I call this method with MyClass.class). Inside this method :

Class object = Class.forName(myClass.getName());
object.newInstance();

-- the name of the object property is in propertyName et the type in propertyType

m = object.getDeclaredMethod("set" + StringUtils.capitalize(propertyName), propertyType);
m.setAccessible(true);
m.invoke(object, myValue);

I would like to surround this with a try catch because when the property belongs to the superClass, there a NoSuchMethodException (which is really too bad).

What should I do to return an object of MyClass on which I can call getId() method?

Thanks





Aucun commentaire:

Enregistrer un commentaire