mardi 2 juillet 2019

Getting the super class field using subclass using reflection

Basically, my requirement is to get the superclass object by using reflection so that i can get the field name and its value.

so, I have a class as

Class Emp {
  private firstName;
  priavte lastName;
}

Class Dept extend Emp {
  private dpFirstName;
  priavte dpLastName;
}

and now am using

emp.getClass.getSuperClass

which give me the java.lang.Class type of the Dept class Now when i try to access the field by using the following code.

Class<?> fields = emp.getClass.getSuperClass;
for (Field field : fields.getDeclaredFields()) {
  field.setAccessible(true);             
  System.out.println(field.get(emp.getClass.getSuperClass));
}

It throws me exception as

Can not set java.lang.String field com.Dept.dpFirstName to java.lang.Class

can anyone help me how can I convert it into an object and so that I can access the filed





Aucun commentaire:

Enregistrer un commentaire