0

Is there any way to list all abstract classes within a java package? For example, in java.lang package.

Ricardo Cristian Ramirez
  • 1,194
  • 3
  • 20
  • 42

2 Answers2

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,389
  • 6
  • 56
  • 67
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
  • 274,122
  • 60
  • 696
  • 724