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.)
1. When a class is loaded in Java. Classloading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need for class initialization occurs.
The extension class loader loads from the JDK extensions directory, usually the $JAVA_HOME/lib/ext directory, or any other directory mentioned in the java. ext. dirs system property.
4. Which of these class defines how the classes are loaded? Explanation: None.
We can check for the existence of a class using Java Reflection, specifically Class. forName(). The documentation shows that a ClassNotFoundException will be thrown if the class cannot be located.
(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"
You can use the findLoadedClass(String) method in ClassLoader. It returns null if the class is not loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With