简体   繁体   English

在超类和子类之间进行等效测试,而无需实例化子类

[英]Doing equivalent test between superclass and subclass without instantiating the subclass

Just playing with java fundamentals I came up with question whether I can check inheritance between two .class objects without instantiating them. 只是在使用Java基础知识时,我想到了是否可以在不实例化它们的情况下检查两个.class对象之间的继承关系的问题。

For example, if I have a class Foo, which is a subclass of Baa: Foo a = new Foo(); return a instanceof Baa 例如,如果我有一个Foo类,它是Baa的子类: Foo a = new Foo(); return a instanceof Baa Foo a = new Foo(); return a instanceof Baa will return true. Foo a = new Foo(); return a instanceof Baa将返回true。

But what do I have to do if I wanna do the equivalent test with Foo.class and Baa.class? 但是,如果我想对Foo.class和Baa.class进行等效测试,该怎么办? I think I can do something like this: Foo.class.newInstance() instanceof Baa.class But would it be possible to test the same without instantiating Foo? 我想我可以做这样的事情: Foo.class.newInstance() instanceof Baa.class但是可以在不实例化Foo的情况下进行测试吗?

You can use Class.isAssignableFrom(Class) to check the hierarchy in inheritance. 您可以使用Class.isAssignableFrom(Class)来检查继承中的层次结构。 According to java-docs: 根据java-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. 确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是该类或接口的超类或超接口。

This will not instantiate any of the classes and you will get the desired functionality. 这不会实例化任何类,您将获得所需的功能。

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

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