自己写一个web服务器,发现class.forName用不了,找不到类,原因是找不到类路径,
可以过加载需要的类的文件路径,然后再通过ClassLoader来加载所需要的类。其中的原
理就不多说了,下面给出代码:
URL url=new URL("类所在文件夹的路径"); String classname=“要加载的类名”; ClassLoader cl=new URLClassLoader(new URL[]{url}); Class d=cl.loadClass(classname);
//将加载的类实例化 Object action=Class.forName(classname).newInstance(); Method method=action.getClass().getMethod("classname类的方法",参数类型); method.invoke(action,参数);