简体   繁体   中英

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?

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM