java Class.forName 给出 ClassNotFound 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12621231/
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-31 09:36:00  来源:igfitidea点击:

Class.forName is giving ClassNotFound Exception

java

提问by Sashi Kant

I am using the following code ::

我正在使用以下代码::

String className  = "SmsHelper"
Class c = Class.forName(className); 

And I am getting the following

我得到以下信息

stackTrace ::

堆栈跟踪 ::

 inside main java.lang.ClassNotFoundException: SmsURLHelper
    at java.net.URLClassLoader.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.tcs.sms.actions.SmsUtil.invoke(SmsUtil.java:131)

Note : The SmsHelper class is present.

注意:存在 SmsHelper 类。

Please suggest if I have missed any thing.

如果我错过了什么,请提出建议。

回答by Mik378

Use the fully qualified name.

使用完全限定的名称。

Example:

例子:

Class.forName("com.yourownpackage.SmsHelper"); 

回答by Arun Kumar

Please write the Class name along with its package name(in which your class resides) as a String in the forNamemethod. Here is the sample to use:

请在forName方法中将类名及其包名(您的类所在的包名)写成一个字符串。这是要使用的示例:

String className  = "com.testpackage.SmsHelper";
Class c = Class.forName(className); 

回答by hmakholm left over Monica

  1. class.forName()expects a fully qualified class name -- such as com.tcs.foo.bar.SmsURLHelper.

  2. Why not just write SmsHelper.class-- that will be checked at compile time, compiled to an appropriate call to class.forName().

  1. class.forName()需要一个完全限定的类名——例如com.tcs.foo.bar.SmsURLHelper.

  2. 为什么不直接写SmsHelper.class——这将在编译时检查,编译为对 class.forName() 的适当调用。