[英]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;
}
How is this achieved? 这是如何实现的?
Looks like you need the isAssignableFrom method 看起来你需要isAssignableFrom方法
if (kelass.isAssignableFrom(klass)) {
objects.add(x);
}
JavaDoc 的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.
确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是它们的超类或超接口。 It returns true if so;
如果是这样,它返回true; otherwise it returns false.
否则返回false。 If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object;
如果此Class对象表示基本类型,则如果指定的Class参数恰好是此Class对象,则此方法返回true;否则返回true。 otherwise it returns false.
否则返回false。
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.
具体来说,此方法测试是否可以通过标识转换或扩展引用转换将指定的Class参数表示的类型转换为此Class对象表示的类型。 See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.
有关详细信息,请参阅Java语言规范,第5.1.1和5.1.4节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.