Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassNotFoundException for a specified class

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?

like image 564
Avraam Mavridis Avatar asked Oct 30 '13 06:10

Avraam Mavridis


People also ask

How do I fix Java Lang NoClassDefFoundError error?

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.

How do I fix class not found exception in eclipse?

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.

Which method throws the ClassNotFoundException?

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 .


2 Answers

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 imports in the calling class play any role.

like image 193
Henry Avatar answered Sep 30 '22 10:09

Henry


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

like image 28
Aniket Kulkarni Avatar answered Sep 30 '22 09:09

Aniket Kulkarni