如何检查作为Class对象的参数的instanceof? [英] How to check instanceof on an argument that is a Class object?
问题描述
我试图建立一个通用类加载器。我需要检查我加载的方法参数的类,以确定它们是否是同一个类。
I'm trying to build a generic class loader. I need to check classes that I load against a method argument to determine if they are of the same class.
代码主要解释我想要做什么。
The code mostly explains what I'm trying to do.
private static LinkedList<Object> loadObjectsInDirectory(Class class0, File dir) throws ClassNotFoundException {
LinkedList<Feature> objects = new LinkedList<Object>();
ClassLoader cl = new GenericClassLoader();
for(String s : dir.list()) {
Class class1 = cl.loadClass(s);
try {
Object x = class1.newInstance();
if (x instanceof (!!! class0 !!!) ) {
objects.add(x);
}
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
}
}
return objects;
}
如何实现?
推荐答案
看起来您需要 isAssignableFrom 方法
if (kelass.isAssignableFrom(klass)) {
objects.add(x);
}
JavaDoc
确定由此Class对象表示的类或接口是否与由指定的Class参数表示的类或接口相同,或者是超类或超接口。如果是这样,返回true;否则返回false。如果这个Class对象表示一个原始类型,如果指定的Class参数正是这个Class对象,那么此方法返回true;
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.
具体来说,此方法测试由指定的Class参数表示的类型是否可以通过身份转换转换为由此Class对象表示的类型,通过扩展参考转换。有关详细信息,请参阅Java语言规范第5.1.1和5.1.4节。
Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.
这篇关于如何检查作为Class对象的参数的instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!