开发者

Java Class.forName failing

开发者 https://www.devze.com 2023-03-01 13:32 出处:网络
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 website throws the exception.

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 website throws the exception.

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

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


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:

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


Your snippet works fine for me.

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

Note that you need to provide the fully qualified name of 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.

(Note that the import is unnecessary.)


Class.forName function needs the fully specified class path. So even if you have imported ArrayList from java.util you should use:

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

that is your problem.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号