繁体   English   中英

使用反射使用超类获取子类字段?

[英]Getting sub class fields using super class using reflection?

我有一个课程如下。

public class Emp{

 private String name;
 private String age;

 //setters and getters

}

下面还有一节课。

public class Student extends Emp{
 private int marks;
 //setters and getters
}

无论如何使用java Reflection使用超类来获取子类的字段? 我需要使用Emp实例获取Student字段。

我们可以得到如下的超类字段:

subClass.getClass().getSuperclass().getDeclaredFields();

同样可以使用超类获取子类字段吗?

可能吗?

谢谢!

我可能误解了你的问题。 你想做以下的事吗?

 Emp e = new Student(...);
 [do something with e]
 foo = e.marks;

如果是,请这样做:

 foo = ((Emp)e).marks;

但是,如果您想执行以下操作:

 Emp e = new Emp(...);
 [do something with e]
 e.marks = ....

然后不,这是不可能的,我怀疑你的java对象模型的内部模型是不完整的还是有缺陷的。

理论上,通过检索所有已加载的类并检查哪些是从Emp派生并包含该字段,有一种非常复杂和昂贵的方法。 如果没有加载所需的类,这可能也无济于事。

不是直接的,你必须写一个辅助方法。

您将类和字段名称(可能还有类型)作为参数,然后在给定的类中查找该字段。 如果你找不到它,你可以从班级的超类中重复一遍。 在您找到该字段之前执行此操作,或者getSuperClass()返回null(意味着您已到达继承树的根目录)。

此示例演示如何在对象上调用find并调用指定的方法 您可以轻松地提取和调整字段的逻辑。

public static Object call(final Object instance,
                          final String methodName,
                          final Class<?>[] signature,
                          final Object[] args) {
    try {
        if (instance == null)
            return null;
        Class<?> instanceClass = instance.getClass();
        while (instanceClass != null) {
            try {
                final Method method = instanceClass.getDeclaredMethod(methodName, signature);
                if (!method.isAccessible())
                    method.setAccessible(true);
                return method.invoke(instance, args);
            } catch (final NoSuchMethodException e) {
                // ignore
            }
            instanceClass = instanceClass.getSuperclass();
        }
    } catch (final Throwable e) {
        return null;
    }
    return null;
}

这是你想要的吗? 但要注意使用field.setAccesible。

家长班:

public class ParentClass {
       private String parentField = "parentFieldValue";
       public void printFields() throws IllegalAccessException {
             Field[] fields = getClass().getDeclaredFields();
             for (Field field : fields) {
                    field.setAccessible(true);
                    Object fieldValue = field.get(this);
                    if (fieldValue instanceof String) {
                           String stringValue = (String) fieldValue;
                           System.out.println(stringValue);
                    }
             }
       }
}

儿童班:

public class ChildClass extends ParentClass {    
       private String childField = "childFieldValue";
}

用法:

public class Main {
       public static void main(String[] args) throws IllegalAccessException {
             ParentClass pc = new ParentClass();
             ChildClass cc = new ChildClass();
             pc.printFields();
             cc.printFields();
       }
}

这是最终的解决方案!

    @NonNull
    public static List<Class<?>> getSubClasses() {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        String method = trace[3].getMethodName();
        if (!"<init>".equals(method)) {
            throw new IllegalStateException("You can only call this method from constructor!");
        }
        List<Class<?>> subClasses = new ArrayList<>();
        for (int i = 4; i < trace.length; i++) {
            method = trace[i].getMethodName();
            if ("<init>".equals(method)) {
                try {
                    subClasses.add(Class.forName(trace[i].getClassName()));
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            } else {
                break;
            }
        }
        return subClasses;
    }

这是一些用法示例:

class a {
public a(){
print(getSubClasses());
}
}
class b extends a{
}
class c extends b{
}

结果是

new a() -> []
new b() -> [b.class]
new c() -> [b.class, c.class]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM