![](/img/trans.png)
[英]Getting actual generic types of “super super” class or interface using reflection
[英]Getting the super class field using subclass using reflection
基本上,我的要求是通过使用反射来获取超类对象,以便我可以获取字段名称及其值。
所以,我有一堂课
Class Emp {
private firstName;
priavte lastName;
}
Class Dept extend Emp {
private dpFirstName;
priavte dpLastName;
}
现在正在使用
emp.getClass.getSuperClass
这给了我Dept类的java.lang.Class类型现在,当我尝试使用以下代码访问该字段时。
Class<?> fields = emp.getClass.getSuperClass;
for (Field field : fields.getDeclaredFields()) {
field.setAccessible(true);
System.out.println(field.get(emp.getClass.getSuperClass));
}
它使我感到异常
Can not set java.lang.String field com.Dept.dpFirstName to java.lang.Class
谁能帮助我如何将其转换为对象,以便我可以访问文件
您的问题是您获得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
}
假定代码的有效版本如下所示:
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));
}
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));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.