In my main I have the following statement
Class booki = Class.forName("Book");
which throws a java.lang.ClassNotFoundException
exception
when I use the full path like Class booki = Class.forName("javatests.Book");
it is ok.
The main class and the Book class are in the same package, I also tried using import static javatests.Book.*;
but still it throws the exception if I don't set the full path javatests.Book
. Can someone explain to me why?
You can fix NoClassDefFoundError error by checking following: Check the exception stack trace to know exactly which class throw the error and which is the class not found by java.
click on project->properties->Java build path->Source and check each src folder is still valid exist or recently removed. Correct any missing path or incorrect path and rebuild and run the test. It will fix the problem.
Class ClassNotFoundException. Thrown when an application tries to load in a class through its string name using: The forName method in class Class . The findSystemClass method in class ClassLoader .
Class.forName
resolves a fully qualified class name to the class. Since a method does not know where it is called from neither the package of the calling class nor import
s in the calling class play any role.
From docs Class#forName
public static Class<?> forName(String className)
throws ClassNotFoundException
Parameters:
className - the fully qualified name of the desired class.
So this will not throw ClassNotFoundException
Class booki = Class.forName("javatests.Book");
For example, it is not needed to import java.lang.*
package in java program but to load class Thread
from java.lang
package you need to write
Class t = Class.forName("java.lang.Thread");
the above code fragment returns the runtime Class descriptor for the class named java.lang.Thread
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