jeudi 24 janvier 2019

Loading dependency jars into classloader

Background: I have custom annotation, which can be used as part of methods. I want to read my custom annotation from the list of .class files. The dependencies(all jars) of these class files are exists in different folder.

Problem: while I was trying to read the all .class files using reflections, getting classnotfoundexception. Below is the code to upload jars and .class files to classloader.

List<URL> urlList = new ArrayList<>();
        File jarsPath = new File("C:/Project/temp/lib");
        urlList.add(jarsPath.toURI().toURL());
        File classFilesPath = new File("C:/Project/build/classess");
        urlList.add(classFilesPath.toURI().toURL());
        URLClassLoader classLoader = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()]), ClasspathHelper.staticClassLoader());
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forClassLoader(classLoader))
                .addClassLoader(classLoader)
                .setScanners(new MethodAnnotationsScanner()));
        Set<Method> methods =  reflections.getMethodsAnnotatedWith(MyAnnotation .class);

Its able to read all .class files and throwing classnotfoundexception when tried to read MyAnnotation.class. Its working as expected if it does not have any dependencies.

Classloader is not finding the classes from jars. Am I missing any thing? Is there any better to achieve this.





Aucun commentaire:

Enregistrer un commentaire