Search code examples
javaclassloader

In Java, is it possible to know whether a class has already been loaded?


Is it possible to know whether a Java class has been loaded, without attempting to load it? Class.forName attempts to load the class, but I don't want this side effect. Is there another way?

(I don't want to override the class loader. I'm looking for a relatively simple method.)


Solution

  • (Thanks to Aleksi) This code:

    public class TestLoaded {
         public static void main(String[] args) throws Exception {
              java.lang.reflect.Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[] { String.class });
              m.setAccessible(true);
              ClassLoader cl = ClassLoader.getSystemClassLoader();
              Object test1 = m.invoke(cl, "TestLoaded$ClassToTest");
              System.out.println(test1 != null);
              ClassToTest.reportLoaded();
              Object test2 = m.invoke(cl, "TestLoaded$ClassToTest");
              System.out.println(test2 != null);
         }
         static class ClassToTest {
              static {
                   System.out.println("Loading " + ClassToTest.class.getName());
              }
              static void reportLoaded() {
                   System.out.println("Loaded");
              }
         }
    }
    

    Produces:

    false
    Loading TestLoaded$ClassToTest
    Loaded
    true
    

    Note that the example classes are not in a package. The full binary name is required.

    An example of a binary name is "java.security.KeyStore$Builder$FileBuilder$1"