关于Class.forName()出现ClassNotFoundException错误!

package c11;


interface HasBatteries {

}


interface Waterproof {

}


interface ShootsThings {

}


class Toy {

// Comment out the following default

// constructor to see

// NoSuchMethodError from (*1*)

Toy() {

}


Toy(int i) {

}

}


class FancyToy extends Toy implements HasBatteries, Waterproof, ShootsThings {

FancyToy() {

super(1);

}

}


public class ToyTest {

public static void main(String[] args) {

Class c = null;

try {

c = Class.forName("FancyToy");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

printInfo(c);

Class[] faces = c.getInterfaces();

for (int i = 0; i < faces.length; i++)

printInfo(faces[i]);

Class cy = c.getSuperclass();

Object o = null;

try {

// Requires default constructor:

o = cy.newInstance(); // (*1*)

} catch (InstantiationException e) {

} catch (IllegalAccessException e) {

}

printInfo(o.getClass());

}


static void printInfo(Class cc) {

System.out.println("Class name: " + cc.getName() + "  is interface? ["

+ cc.isInterface() + "]");

}

} // /:~

java.lang.ClassNotFoundException: FancyToy

at java.net.URLClassLoader$1.run(Unknown Source)

at java.net.URLClassLoader$1.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 c11.ToyTest.main(ToyTest.java:33)

经过我查看手册,发现一下描述:

  • 参数:

  • className - 所需类的完全限定名。

  • 返回:

  • 具有指定名的类的 Class 对象。

  • 抛出:

  • LinkageError - 如果链接失败

  • ExceptionInInitializerError - 如果此方法所激发的初始化失败

  • ClassNotFoundException - 如果无法定位该类


好吧,手册上明明白白,清清楚楚的写了需要完全限定名。所以必须为forName方法的变量使用完全限定名的类名。

你可能感兴趣的:(关于Class.forName()出现ClassNotFoundException错误!)