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
Java Class.forName failing
提问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 A
is 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.forName
function needs the fully specified class path. So even if you have imported ArrayList
from java.util
you 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”的类