Java反射:查找子类的字段 [英] Java reflection: Find fields of a subclass

查看:121
本文介绍了Java反射:查找子类的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类层次结构如下:(=>表示是的子类)

I have a class hierarchy like so: (=> means "is a subclass of")

anonymous instance class => abstract class => generic abstract class

或更简洁:

C => B => A

执行时,C调用A方法之一。在A中的该方法中,我想使用反射来查找在类B中定义的对象的受保护字段。 (所以这些是C和B可以看到的字段,但不是A。)

When executing, "C" calls one of "A"'s methods. Within that method in "A", I want to use reflection to find protected fields of the object that are defined in class "B". (So these are fields that "C" and "B" can see, but not "A".)

我如何用Java反射做到这一点?如果我在A& A之间添加一些东西,我怎么能面向未来呢? B或B& C?

How would I do this with Java reflection? And how can I future-proof it in case I add something between A & B or B & C?

推荐答案

你必须使用 getDeclaredFields() 您的对象的类(通过 getSuperclass() )。

You have to use getDeclaredFields() repeatedly on each class in the inheritance hierarchy of your object's class (via getSuperclass()).

然而,你的计划听起来像是一个令人讨厌的违反继承概念的行为。面向未来的最佳方法是完全避免这种事情。 你试图做什么,你认为需要这样的反思恶作剧?

However, what you are planning sounds like a nasty violation of the concept of inheritance. The best way of future-proofing would be to avoid this kind of thing entirely. What are you trying to do that you think requires such reflection shenanigans?

这篇关于Java反射:查找子类的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆