3 回答
TA贡献1780条经验 获得超5个赞
您的问题是您获得了超类,Emp但没有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>
因此,您可以使用以下代码片段作为正确示例:
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
}
TA贡献1799条经验 获得超9个赞
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));
}
}
}
TA贡献1824条经验 获得超8个赞
假设您的代码的有效版本如下所示:
class Emp {
private String firstName;
private String lastName;
}
class Dept extends Emp {
private String dpFirstName;
private String dpLastName;
}
编辑:忘记演员表,没有它就可以工作。
Class<?> fields = emp.getClass().getSuperclass();
for (Field field : fields.getDeclaredFields()) {
field.setAccessible(true);
System.out.println(field.getName() + "\t" + field.get(emp));
}
添加回答
举报