adamw7 / tools

code generation and data oriented tools
MIT License
5 stars 1 forks source link

Reflection does not work while used from other project #31

Closed adamw7 closed 1 year ago

adamw7 commented 1 year ago

https://github.com/ronmamo/reflections/issues/373

adamw7 commented 1 year ago

Solved by extending the classpath, reflections are ok

chaitanyachinta55 commented 1 year ago

how is this issue resolved, please help us example or guidance. we are still facing issues.

reflcation API is not scanning classes with custom annotations

adamw7 commented 1 year ago

It turned out the reflection was working fine:

        Reflections reflections = new Reflections(new ConfigurationBuilder().forPackages(pkg));
        Set<Class<? extends GeneratedMessageV3>> classes = reflections.getSubTypesOf(GeneratedMessageV3.class);

What I had to to in order to make it work from other projects was additional code in mojo:

private void extendClassPath() {
        try {
            Set<URL> urls = new HashSet<>();
            List<String> elements = project.getRuntimeClasspathElements();

            for (String element : elements) {
                if (element != null) {
                    urls.add(new File(element).toURI().toURL());                    
                }
            }

            ClassLoader contextClassLoader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]),
                    Thread.currentThread().getContextClassLoader());

            Thread.currentThread().setContextClassLoader(contextClassLoader);
        } catch (DependencyResolutionRequiredException | MalformedURLException e) {
            throw new RuntimeException(e);
        } 
    }