简体   繁体   中英

Class.forName(“FQN”) throws ClassNotFoundException Intermittently

I have a Java based RMI Server in which one of the interface method is like this :

public Properties process(String operation, Properties params) {
         Class nodecls = Class.forName("com.example.commands." + operation);
   } 

This method runs fine all the time but sometimes (say once in a million RMI calls) throws ClassNotFoundException . What could be the reason for this? I am sure that the name passed is correct.

From XYZWS - What does Class forname method do? :

A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (ie, JVM executes all its static block after class loading). Class.forName("X") returns the Class object associated with the "X" class. The returned Class object is not an instance of the "x" class itself.

Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name of the desired class.

The tag wiki for has a simpler description:

The Java exception thrown when an application tries to load a class by name. Usually raised by one of:

  • the forName method in class Class [...]

when no definition for the class with the specified name could be found in the classpath.

Therefore, there can only be two causes for this:

  1. The class named "com.example.commands." + operation "com.example.commands." + operation is not present on the Class Path.
  2. The ClassLoader of the Class which your method is in cannot find the "com.example.commands." + operation "com.example.commands." + operation class. Maybe some reflection trick broke it.

However, you should never have to bother with this, as your method wouldn't even compile - it's of a non- void return type, while you never included a proper return statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM