Search code examples
javareflections

can someone help me to know jdk version compatibility on org.reflections.Reflections jar


I m using Reflections.jar for the first time, so i like to know the following

  • Is there any version compatibility for this jar(like above jdk6 (or) upto jdk8)
  • While loading classes is there any order of loading(like alphabetical order (or) order of jar placed in classpath)

Solution

  • If you are talking about this https://github.com/ronmamo/reflections project then it find the classes in the order they appear in your classpath like the Java launcher would do. The way how classes are found and loaded is described here https://docs.oracle.com/javase/8/docs/technotes/tools/findingclasses.html.

    The first class file in the classpath order which matches the full class name is loaded. Find a small snippet below for demonstration.

    assume following directories and files

    lib/annotations-2.0.1.jar
    lib/guava-15.0.jar
    lib/javassist-3.18.2-GA.jar
    lib/reflections-0.9.9.jar
    src/DummyInterface.java
    src/Main.java
    src1/DummyClass1.java
    src2/DummyClass1.java
    

    src/DummyInterface.java

    package sub.optimal;
    public interface DummyInterface {}
    

    src/Main.java

    import org.reflections.Reflections;
    import sub.optimal.DummyInterface;
    public class Main {
        public static void main(String[] args) throws Exception {
            Reflections reflections = new Reflections("sub.optimal");
            for (Class c : reflections.getSubTypesOf(DummyInterface.class)) {
                System.out.println("class: " + c.getCanonicalName());
                c.newInstance();
            }
       }
    }
    

    src1/DummyClass1.java

    package sub.optimal;
    public class DummyClass1 implements DummyInterface {
        static {
            System.out.println("touched DummyClass 1");
        }
    }
    

    src2/DummyClass1.java

    package sub.optimal;
    public class DummyClass1 implements DummyInterface {
        static {
            System.out.println("touched DummyClass 2");
        }
    }
    

    first compile the classes, for the demonstration we create the class files in different locations

    javac -cp lib/* -d bin/ src/DummyInterface.java src/Main.java
    javac -cp bin/:lib/* -d bin1/ src1/DummyClass1.java
    javac -cp bin/:lib/* -d bin2/ src2/DummyClass1.java
    

    executing Main with bin1/ before bin2/ in the class path will find and load the DummyClass1 in bin1/

    java -cp bin/:bin1/:bin2/:lib/* Main
    

    output

    class: sub.optimal.DummyClass1
    touched DummyClass 1
    

    executing Main with bin2/ before bin1/ in the class path will find and load the DummyClass1 in bin2/

    java -cp bin/:bin2/:bin1/:lib/* Main
    

    output

    class: sub.optimal.DummyClass1
    touched DummyClass 2