简体   繁体   中英

Loading the classes from a jar that is dynamically uploaded through a servlet

I am uploading a jar dynamically through servlet and saving it in my WEB-INF/lib directory. I want to get all the classes annotated with my @annotation,

have used reflections code below without any luck.. the manifest of the jar is readble but the classes are not.. the list of classes is 0

List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
ConfigurationBuilder builder = new ConfigurationBuilder().setScanners(new SubTypesScanner(false), new ResourcesScanner(),
new TypeAnnotationsScanner());
Set<URL> set = ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]));
        FilterBuilder filterBuilder = new FilterBuilder().include(FilterBuilder.prefix(exportPackage));
        Reflections reflections = new Reflections(builder.setUrls(set).filterInputsBy(filterBuilder));

        Set<Class<? extends Object>> classSet = reflections.getTypesAnnotatedWith(MyAnnotation.class);

What changes to the configuration will help get the classes from the jar that is dynamically uploaded..

Since you are updating your own WEB-INF/lib directory it is not necessarily caught by your context class loader. BTW I think it is a bad practice: the behavior depends on the application server and this directory is probably not writable and even probably does not exist if you are running from war...

So, I'd put the jar to other directory and use my custom class loader. It is not so hard. You can use regular UrlClassLoader . Just configure it to read classes from correct path. Once this is done pass this class loader when you are creating instance of Reflections . Take a look on its javadcoc. The constructor can except various types of parameters including class loader.

from your listener class (or from wherever servletContext is available), try using:

new Reflections(ClasspathHelper.forWebInfClasses(servletContext))

or

new Reflections(ClasspathHelper.forWebInfLib(servletContext))

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