如何通过反射确定Java类是否是抽象的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1072890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I determine whether a Java class is abstract by reflection
提问by peter.murray.rust
I am interating through classes in a Jar file and wish to find those which are not abstract. I can solve this by instantiating the classes and trapping InstantiationException but that has a performance hit as some classes have heavy startup. I can't find anything obviously like isAbstract() in the Class.java docs.
我正在通过 Jar 文件中的类进行交互,并希望找到那些不是抽象的。我可以通过实例化类并捕获 InstantiationException 来解决这个问题,但是由于某些类启动繁重,这会影响性能。我在 Class.java 文档中找不到任何明显像 isAbstract() 的东西。
采纳答案by seth
It'll have abstract as one of its modifiers when you call getModifiers() on the class object.
当您在类对象上调用 getModifiers() 时,它会将抽象作为其修饰符之一。
This linkshould help.
这个链接应该有帮助。
Modifier.isAbstract( someClass.getModifiers() );
Also:
还:
http://java.sun.com/javase/6/docs/api/java/lang/reflect/Modifier.html
http://java.sun.com/javase/6/docs/api/java/lang/reflect/Modifier.html
http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getModifiers()
http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getModifiers()
回答by Stobor
Class myClass = myJar.load("classname");
bool test = Modifier.isAbstract(myClass.getModifiers());
回答by Abdushkur Ablimit
public static boolean isInstantiable(Class<?> clz) {
if(clz.isPrimitive() || Modifier.isAbstract( clz.getModifiers()) ||clz.isInterface() || clz.isArray() || String.class.getName().equals(clz.getName()) || Integer.class.getName().equals(clz.getName())){
return false;
}
return true;
}