Is there any way to list all abstract classes within a java package? For example, in java.lang package.
Asked
Active
Viewed 589 times
2 Answers
1
via reflection get the list of classes int the package, and then check if the class is abstract by doing
Modifier.isAbstract( theClass.getModifiers() );
Can you find all classes in a package using reflection?
How can I determine whether a Java class is abstract by reflection
Community
- 1
- 1
Frederic Close
- 9,123
- 6
- 54
- 64
1
With Guava's ClassPath class you can list all top level classes in a package. You can then use the Modifier class to find out if the class is abstract.
Here's a small example
public static void main(String[] args) throws IOException {
ClassPath p = ClassPath.from(ClassLoader.getSystemClassLoader()); // might need to provide different ClassLoader
ImmutableSet<ClassInfo> classes = p.getTopLevelClasses("com.example");
for (ClassInfo classInfo : classes) {
Class clazz = classInfo.load();
int modifiers = clazz.getModifiers();
if (Modifier.isAbstract(modifiers)) {
System.out.println("Class '" + clazz.getName() + "' is abstract.");
}
}
}
Sotirios Delimanolis
- 263,859
- 56
- 671
- 702