简体   繁体   English

Class.forName()和ClassNotFoundException

[英]Class.forName() and ClassNotFoundException

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. (如果我要删除类MyClass ,我将得到一个ClassNotFoundException ,如预期的那样。

However, if they are both in a package (let's say it's a package in Eclipse), and have the 但是,如果它们都在一个包中(假设它是Eclipse中的一个包),并且具有

package myClassTestPackage;

declared in both, I get a ClassNotFoundException when I try to run it. 在这两个声明中,当我尝试运行它时都会收到ClassNotFoundException

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. 这是我能够重现在更大程序中遇到的错误的最简单方法。

That's because the Class.forName() method takes the fully qualified class name as parameter. 这是因为Class.forName()方法将完全限定的类名作为参数。

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

So: 所以:

Class.forName("myClassTestPackage.MyClass");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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