JohnWinter
JohnWinter

Reputation: 1023

How to speed up the class scan via Reflection API in Java?

I use org.reflections library to scan ClassPath and get classes. Here is my code:

Reflections ref = new Reflections();
Set<Class<? extends Service>> classes = new HashSet<>();
for (Class<? extends Service> subType : ref.getSubTypesOf(Service.class)) {
    if (!Modifier.isAbstract(subType.getModifiers())) {
        classes.add(subType);
    }
}

But I faced a problem. It takes too much time. At the same time I can not set a package

new Reflections("my.pack");

because I want to save an ability to add Service classes in the future. How can I accelerate this process? Is it possible to exclude rt.jar packs?

Upvotes: 1

Views: 676

Answers (1)

weston
weston

Reputation: 54791

Use FilterBuilder to exclude java root package at least.

And it may help to specify SubTypesScanner as that's what you're doing.

Reflections ref = new Reflections(new SubTypesScanner(),
                                  new FilterBuilder().excludePackage("java"));

Upvotes: 3

Related Questions