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.
Asked
Active
Viewed 6.0k times
3 Answers
345
It'll have abstract as one of its modifiers when you call getModifiers() on the class object.
This link should 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/Class.html#getModifiers()

seth
- 36,759
- 7
- 60
- 57
-
1Thanks! One little note: You can't use "class" as a variable name, maybe you want to change your example. – Tim Büthe Nov 24 '10 at 17:07
-
1@seth I think it should be `Modifier.isAbstract( someClass.class.getModifiers() );` maybe you want to change that – steven7mwesigwa Jan 05 '19 at 00:36
-
According to normal Java naming conventions it is either `someClass.getModifiers()` or `SomeClass.class.getModifiers()` where `Class
someClass = SomeClass.class;` – neXus Jan 23 '19 at 14:48
35
Class myClass = myJar.load("classname");
bool test = Modifier.isAbstract(myClass.getModifiers());

Stobor
- 44,246
- 6
- 66
- 69
2
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;
}

Abdushkur Ablimit
- 41
- 2
-
if it is a interface and class name is java.util.List you might as will create ArrayList – Abdushkur Ablimit Dec 21 '17 at 19:47