Java Class.forName failing

2019-05-11 02:40发布

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?

4条回答
我命由我不由天
2楼-- · 2019-05-11 03:02

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.

查看更多
Evening l夕情丶
3楼-- · 2019-05-11 03:17

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

查看更多
你好瞎i
4楼-- · 2019-05-11 03:19

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");
查看更多
倾城 Initia
5楼-- · 2019-05-11 03:20

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.)

查看更多
登录 后发表回答