1

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..

Komal Goyal
  • 233
  • 5
  • 17

2 Answers2

0

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.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • I created a UrlClassLoader and added it to the classLoadersList but the issues still remains.. trying to load a class throws ClassNotFoundException.. I have also separated the jar from the lib not storing the uploaded jar in a separate folder.. can you help me with some sample code of urlclassloader with reflections..? – Komal Goyal Dec 13 '12 at 06:06
0

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

new Reflections(ClasspathHelper.forWebInfClasses(servletContext))

or

new Reflections(ClasspathHelper.forWebInfLib(servletContext))
zapp
  • 1,533
  • 1
  • 14
  • 18