Reputation: 111
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
Upvotes: 0
Views: 881
Reputation: 4259
Assuming that the valid version of your code looks like that:
class Emp {
private String firstName;
private String lastName;
}
class Dept extends Emp {
private String dpFirstName;
private String dpLastName;
}
Edit: Foget about the cast, works without it.
Class<?> fields = emp.getClass().getSuperclass();
for (Field field : fields.getDeclaredFields()) {
field.setAccessible(true);
System.out.println(field.getName() + "\t" + field.get(emp));
}
Upvotes: 0
Reputation: 18255
Your problem is that you get superclass for Emp
but not Dept
.
Emp emp = new Emp();
Dept dept = new Dept();
Class<?> cls = emp.getClass().getSuperclass(); // it is Class<Object>
Class<?> cls = dept.getClass().getSuperclass(); // it is Class<Emp>
So, you can use the following snippet as a correct example:
class Emp {
private String firstName = "first_name";
private String lastName = "last_name";
}
class Dept extends Emp {
private String dpFirstName = "dp_first_name";
private String dpLastName = "dp_last_name";
}
public static void getSuperClassFields(Dept dept) throws IllegalAccessException {
Class<?> cls = dept.getClass().getSuperclass();
for (Field field : cls.getDeclaredFields()) {
field.setAccessible(true);
System.out.println(field.getName() + " = " + field.get(dept));
}
}
public static void main(String[] args) throws IllegalAccessException {
getSuperClassFields(new Dept());
// in console you can see
// firstName = first_name
// lastName = last_name
}
Upvotes: 1
Reputation: 943
public class Emp {
private String firstName;
private String lastName;
}
public class Dep extends Emp{
private String dpFirstName;
private String dpLastName;
}
public class Main {
public static void main(String[] args) throws Exception {
Dep d = new Dep();
Class<?> c = d.getClass().getSuperclass();
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
if(field.getName().equals("firstName")){
field.set(d, "First Name");
}
if(field.getName().equals("lastName")){
field.set(d, "Last Name");
}
System.out.println(field.getName() + "\t" + field.get(d));
}
}
}
Upvotes: 1