Catch all the classes of a given Package that is in the classpath

2

I'm trying to get all the classes of a particular package, I've seen some code that does this, however, it just takes the classes that are part of the project itself, basically does not use reflection and yes it does a search for .class files in the directory, in my case, I need to get the .class of a jar that is part of my project.

Something like:

List<Class> clazz = ReflectionUtil.getClassFromPackage("org.springframework.util");

List<Class> clazz = ReflectionUtil.getClassFromPackage("com.meuprojeto.meupacotebase");

I've already tried:

link

link

link

link

They talked about this library link

but has the following code:

 Reflections reflections = new Reflections("my.project");

 Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);

Now, I need to get the class list, I do not want to specify the type of class I need

I think this would or should be basic with reflection of Java.

    
asked by anonymous 12.02.2014 / 16:02

1 answer

4

You can use the Reflections library in an unusual way, but you can:

//lista as classes do pacote "com.google", incluindo os subpacotes
Reflections r = new Reflections(
        "com.google", 
        new SubTypesScanner(false),
        ClasspathHelper.forClassLoader()
    );
Set<Class<?>> classes = r.getSubTypesOf(Object.class);

//exibe a lista classes
for (Class<?> c : classes) {
    System.out.println(c.getName());
}

The parameter new SubTypesScanner(false) permite a listagem de classes através de Object.class', that is, classes that have no explicit inheritance. Otherwise these classes would be ignored.

The parameter ClasspathHelper.forClassLoader() lists all classes in the current Class Loader , otherwise only the current project / jar classes will be listed.

Just be careful if any class that can not be loaded (perhaps for lack of dependency), otherwise you end up with an exception like this:

Exception in thread "main" org.reflections.ReflectionsException: could not get type for name org.dom4j.xpath.DefaultNamespaceContext
    at org.reflections.ReflectionUtils.forName(ReflectionUtils.java:378)
    at org.reflections.ReflectionUtils.forNames(ReflectionUtils.java:387)
    at org.reflections.Reflections.getSubTypesOf(Reflections.java:338)
    at snippet.ListClasses.main(ListClasses.java:15)

Another option would be to do everything manually, that is, you can look at classpath in the environment variable and go through all directories looking for .class and jars files that contain the classes you need.

Honestly, it's not worth it. If you do not want to use a library to make it easier, add some constraints to the project to make it easier to list classes.

    
12.02.2014 / 16:48