0

With that I can find the package name within an application

Package pack = Item.class.getPackage();

But all examples which I can find here or elsewhere to find the classes in a package use file to load a jar and look into that. I there a way to gat a classes list within active project without file ?

[EDIT] there are othere answers here but they all didn't work for me

[Edit] is for some reasons this has been blocked for answers. here is the solution

    private static Set<Class<? extends Object>> getClassesInPackage(String packagename) {

    List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
            .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packagename))));

    Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
    return classes;  
} 
user3732793
  • 1,699
  • 4
  • 24
  • 53

1 Answers1

1

It is impossible due to dynamic nature of classloaders. Classloaders do not have to expose all classes they have. The only way might be to write your own classloader and play with the order of classloading so, your classloader will have more info.

However, here is a library that could potentially help you getting classes in the package (never used it but found it just now by googling).

something ike that:

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

Set<Class<? extends Object>> allClasses = 
     reflections.getSubTypesOf(Object.class);
aviad
  • 8,229
  • 9
  • 50
  • 98
  • I replaced the package name with pack.getName() which produced this in the logs...INFO org.reflections.Reflections - Reflections took 62 ms to scan 2 urls, producing 0 keys and 0 values....however it looks promissing. I will have a closer look at the library, thanks – user3732793 Jun 15 '16 at 09:49