Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 329
Hosam Aly Avatar asked Jan 27 '09 08:01

Hosam Aly


People also ask

What happens when a class is loaded in Java?

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.

Where are classes loaded in Java?

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.

Which class defines how the classes are loaded?

4. Which of these class defines how the classes are loaded? Explanation: None.

How do you know if a class is present in classpath?

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.


2 Answers

(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"

like image 199
Stephen Denne Avatar answered Sep 26 '22 07:09

Stephen Denne


You can use the findLoadedClass(String) method in ClassLoader. It returns null if the class is not loaded.

like image 28
Aleksi Yrttiaho Avatar answered Sep 25 '22 07:09

Aleksi Yrttiaho