开发者

Reflection api - find subclass type

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 s开发者_开发百科uperObject, 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.


The getClass() method will return the concrete type of the object at runtime, not the reference type. So simply doing:

Super superObject = new Sub1();
Class<? extends Super> klass = superObject.getClass();

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.


Your question, "is it possible to find which subclass the superObject extends in Java?", is not making any sense.

Anyway, I assume you are looking for Class.isAssignableFrom() might help in this regards.

Usage:

superClass.isAssignableFrom(subClass);

Docs:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

Reference


You want this method:

boolean isList = Subclass.isAssignableFrom(Superclass);

From the JavaDoc:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Reference:

 Class.isAssignableFrom(Class)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜