Java Class.forName 失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5803369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:51:16  来源:igfitidea点击:

Java Class.forName failing

javareflection

提问by user727125

I cannot seem to get Class.forName(String)to not throw a ClassNotFoundException. For example, this code which is a shortened copy of code directly from Sun's websitethrows the exception.

我似乎Class.forName(String)无法不抛出ClassNotFoundException. 例如,此代码是直接来自 Sun 网站代码的缩短副本,会引发异常。

import java.lang.reflect.*;
class A {}

public class Test {
   public static void main(String args[])
   {
      try {
         Class cls = Class.forName("A");
      }
      catch (Throwable e) {
         System.err.println(e);
      }
   }
}

Produces

生产

java.lang.ClassNotFoundException: A

java.lang.ClassNotFoundException: A

I am using Eclipse 1.3.2.20110218-0812 on Windows XP SP3. Does anyone know what I am missing?

我在 Windows XP SP3 上使用 Eclipse 1.3.2.20110218-0812。有谁知道我错过了什么?

回答by Tomasz Stanczak

You have to prepend the package name of the Test class to A, as an example if Test were in "test" package, you'd need following:

您必须将 Test 类的包名称添加到 A 之前,例如,如果 Test 在“test”包中,则需要以下内容:

Class cls = Class.forName("test.A");

回答by aioobe

Your snippet works fine for me.

你的片段对我来说很好用。

Here is a demo at ideone.com: http://ideone.com/IBjKl

这是 ideone.com 上的演示:http://ideone.com/IBjKl

Note that you need to provide the fully qualified nameof the class for the class loader to find it. I.e., if Ais actually in some package, you need to do forName("your.package.A")for it to work.

请注意,您需要为类加载器提供类的完全限定名称才能找到它。即,如果A实际上在某个包中,则您需要执行此操作forName("your.package.A")才能使其工作。

(Note that the import is unnecessary.)

(请注意,导入是不必要的。)

回答by omerkirk

Class.forNamefunction needs the fully specified class path. So even if you have imported ArrayListfrom java.utilyou should use:

Class.forName函数需要完全指定的类路径。因此,即使您ArrayList已从java.util您导入,也应使用:

Class myClass = Class.forName("java.util.ArrayList");

that is your problem.

那是你的问题。

回答by Heiko Rupp

For this to work, you need to have a class with name "A" in your classpath

为此,您需要在类路径中有一个名为“A”的类