How can I determine whether a Java class is abstract by reflection
JavaClassAbstractJava Problem Overview
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.
Java Solutions
Solution 1 - Java
It'll have abstract as one of its modifiers when you call getModifiers() on the class object.
This [link][1] should help.
Modifier.isAbstract( someClass.getModifiers() );
Also:
[http://java.sun.com/javase/6/docs/api/java/lang/reflect/Modifier.html][2]
[http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getModifiers()][3]
[1]: http://java.sun.com/docs/books/tutorial/reflect/class/classModifiers.html "link" [2]: http://java.sun.com/javase/6/docs/api/java/lang/reflect/Modifier.html [3]: http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getModifiers()
Solution 2 - Java
Class myClass = myJar.load("classname");
bool test = Modifier.isAbstract(myClass.getModifiers());
Solution 3 - Java
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;
}