Unable to fetch classes of a package using Reflection

1.2k views Asked by At

enter image description here

From the above image, when i am trying to fetch all classes under "tests", i am getting empty array.

    Reflections reflections = new Reflections("tests");
    //Reflections reflections = new Reflections("src.test.java.tests"); Tried but still empty array

     Set<Class<? extends Object>> allClasses =  reflections.getSubTypesOf(Object.class); //Getting empty array here
     Class[] arrayCls=new Class[allClasses.size()];
     allClasses.toArray(arrayCls);

Can someone please help me how to get array of classes?

2

There are 2 answers

1
mazenaissa On

This solution worked for me, i have a packed named testing under src file which contain directly classes and sub packages with classes and it return to correct set containg the corresponding classes. The first parameter of Reflections constructor must be your packageName appended with a '.' in the end :

   Reflections reflections = new Reflections("testing.", new SubTypesScanner(false));
   Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);

Don't forget to add the corresponding jars to your project : annotations-2.0.1.jar,guava-15.0,javassist-3.19.0-GA,reflections-0.9.10 which you can download them from here https://jar-download.com/artifacts/org.reflections/reflections/0.9.10/source-code.

Update: This will work under tests package. It is based on ClassPath class from Guava 14. The TestNGRunner class loader is used here to fetch the classes placed under the same src package of TestNGRunner which is the src/test/java. The check is done the full name of the class (packageName+.+className) that's why i used startsWith("tests.") :

   final ClassLoader loader = TestNGRunner.class.getClassLoader();
    Set<Class<? extends Object>> allClasses = new HashSet<Class<? extends Object>>();
    for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
      if (info.getName().startsWith("tests.")) {
          allClasses.add(info.load());
      }
    }
0
Mike Rowley On

SubTypesScanner is now depreciated. You can use this instead:

var reflections = new Reflections(packageToScan, SubTypes.filterResultsBy(s -> true));