关于java反射中的Class异常?
下面是java的简单工厂方法我用了java的反射机制。可它老是出现异常啊,上网查了下也没找到解决方法,那位能告诉我是什么原因啊,小弟在此谢了。
public interface Animal {
public void run();
}
public class Tiger implements Animal{
public void Tiger()
{
}
public void run()
{
System.out.println("老虎会跑");
}
public void eat()
{
System.out.println("老虎会吃");
}
}
public class SampleFactory
{
public static Animal createAnimal(String className) throws
ClassNotFoundException,
InstantiationException,
IllegalAccessException {
Class c=Class.forName(className);
Animal animal=(Animal)c.newInstance();
return animal;
}
}
public class Client {
public static void main(String[] args) throws Class
NotFoundException, InstantiationException, IllegalAccessException {
Animal animal=SampleFactory.createAnimal("Tiger");
animal.run();
}
}
异常:
Exception in thread "main"
java.lang.ClassNotFoundException: Tiger
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.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
------解决方案--------------------classpath设置的问题吧?因为你的类没有在classpath里
试试通过用URLClassLoader加载类,获得Class的实例
我没有尝试,也是个初学者,不过lz可以试试我说的方法
------解决方案--------------------补充下上面回答:
URL url = new URL("file:\\" + path + "\\");
URLClassLoader ucl = new URLClassLoader(new URL[]{url});
Class c = ucl.loadClass(classname);