Search code examples
javaintrospection

How to know if a class is from the JRE or from an external Jar?


Does anybody knows if it's possible (is there a library) to know if a Class<?> variable is included in the JRE or not ?

Here is what I would want :

Class<String> stringClass = String.class;
System.out.println(TheMagickLibrary.isJREClass(stringClass)); // should display true

Class<AnyClass> anotherClass = AnyClass.class;
System.out.println(TheMagickLibrary.isJREClass(anotherClass)); // should display false

Solution

  • I can offer you 2 solutions.

    1. Get class package and check whether it starts with java., sun., com.sun.
    2. Get the class' class loader:
    Returns the class loader for the class.  Some implementations may use
    null to represent the bootstrap class loader. This method will return
    null in such implementations if this class was loaded by the bootstrap
    class loader.
    

    As you can see they say "some implmentations may return null". It means that for these implementations clazz.getClassLoader() == null means that the class is loaded by bootstrap class loader and therefore belongs to JRE. BTW this works on my system (Java(TM) SE Runtime Environment (build 1.6.0_30-b12)).

    If not check the documentation of ClassLoader#getParent():

     Returns the parent class loader for delegation. Some implementations may
     use <tt>null</tt> to represent the bootstrap class loader. This method
     will return <tt>null</tt> in such implementations if this class loader's
     parent is the bootstrap class loader.
    

    Again, some implementations will return null if current class loader is a bootstrap.

    Finally I'd recommend the following strategy:

    public static boolean isJreClass(Class<?> clazz) {
        ClassLoader cl = clazz.getClassLoader();
        if (cl == null || cl.getParent() == null) {
            return true;
        }
        String pkg = clazz.getPackage().getName();
        return pkg.startsWith("java.") || pkg.startsWith("com.sun") || pkg.startsWith("sun."); 
    }
    

    I believe this is good enough for 99% of cases.