JoelP
JoelP

Reputation: 439

Get all classnames that extend a specific class

In my java project, I need to get a variable from each class that extends another class. My problem here is that I don't know the name of these classes. Let's say my classtree looks like this:

Package
 - MyProject
 - BaseClass
 - Class 1 extends BaseClass
 - Class 2 extends BaseClass
 - Class 3 extends BaseClass
 - Class 4
 - Class 5

Now each Class that extends BaseClass has a variable baseVariable, and I need to get its value in MyProject. Is there any way to get a list of classes that extend BaseClass, so I can then access the baseVariable value?

Thanks in advance

Upvotes: 1

Views: 128

Answers (2)

Vlad
Vlad

Reputation: 10780

You could use Reflections:

Set<Class<? extends BaseClass>> subclasses = reflections.getSubTypesOf(BaseClass.class);

Upvotes: 2

PeterMmm
PeterMmm

Reputation: 24640

You can do this with ClassPath from Guava.

    ClassPath cp = ClassPath.from(ClassLoader.getSystemClassLoader());
    for (ClassPath.ClassInfo n : cp.getAllClasses()) {
        Class cl = n.load();
        if (BaseClass.isAssignableFrom(cl)) {
        }
    }

Upvotes: 4

Related Questions