Class.forName() and ClassNotFoundException

Deadly 提交于 2019-12-12 20:03:59

问题


Say I have the following two classes:

public class MyClass {
    public String getDescription() {
        return "MyClass";
    }
}

and

public class MyClassLoader {
    public static void main (String[] argv) throws ClassNotFoundException {
        Class.forName("MyClass");
        System.out.println("MyClass class was successfully loaded");
    }
}

If both of these classes are in the default package, it runs fine, the class loads, and the world is beautiful. (If I were to delete the class MyClass, I would get a ClassNotFoundException, as expected.

However, if they are both in a package (let's say it's a package in Eclipse), and have the

package myClassTestPackage;

declared in both, I get a ClassNotFoundException when I try to run it.

What causes this issue and how can I fix it? This is the simplest way I was able to reproduce an error I am experiencing in a much larger program.


回答1:


That's because the Class.forName() method takes the fully qualified class name as parameter.

Parameters:
    className - the fully qualified name of the desired class.

So:

Class.forName("myClassTestPackage.MyClass");


来源:https://stackoverflow.com/questions/13326890/class-forname-and-classnotfoundexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!