Reflection api - 查找子类类型
嗨,我正在尝试找出子类,形成一个超类对象。
if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)
Lets say I have a object of Super type as
Super superObject = new Sub1();
现在对于 superObject,是否可以找到 superObject 在 Java 中扩展了哪个子类?
由于“超类不会知道它拥有的任何子类”,您能否告诉我上面的问题首先是有效,还是我遗漏了任何基本概念? >
提前致谢。
Hi I am trying to find out the subclass, form an superclass object.
if Class Super is the super class.
and Class Sub1 and Class Sub2 extends Class Super.(all classes are public)
Lets say I have a object of Super type as
Super superObject = new Sub1();
now for the superObject, is it possible to find which subclass the superObject extends in Java?
Since "SuperClass will not be aware of any SubClasses it has", can you please tell me is my above question valid in the first place, or am I missing any basic concept?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
getClass() 方法将在运行时返回对象的具体类型,而不是引用类型。所以简单地做:
会给你 Sub1.class 从你的问题中不清楚你想用它做什么。您可以简单地调用 getName() ,检查您拥有的其他引用是否具有相同类型,等等。
The getClass() method will return the concrete type of the object at runtime, not the reference type. So simply doing:
Will give you Sub1.class It's not clear from your question what you then want to do with it. You can simply call getName() on it, check if some other reference you have is of the same type, etc etc.