Java - why does this input not generate ClassNotFoundException

75 views Asked by At

While I am using reflection I came upon this error. I have a class named Test1, and when I try to get a Class object of it by entering test1 as input to Class.forName() it generates LinkageError instead of ClassNotFoundException. Why does the lower-case letter confuse the program and prevent it from generating the usual ClassNotFoundException as with for example "sjghdjgh"?

Minimal example

Main

public class Main {
    public static void main(String[] args) {
        try {
            Class.forName("test1");
        }
        catch (ClassNotFoundException cnfe) {
            System.out.println(cnfe.toString());
        }
        catch (LinkageError le) {
            System.out.println(le.toString());
        }
    }
}

Test1

public class Test1 {
}
1

There are 1 answers

1
Thilo On BEST ANSWER

If you ask some file systems for test1.class they will give you back a Test1.class instead of a file-not-found (because they are case-insensitive) and then that class file does not contain a class called test1, but instead a Test1 (Java class names are case-sensitive), so that the classloader errors out.

This is rarely a problem in practice, because most applications are deployed using Jar files (so that there are no individual files for the classes in the filesystem).