自己寫一個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,參數);
以下是片段代碼:
URL url=new URL("file:\\D:\\Users\\Administrator\\Workspaces\\MyEclipse 8.6\\2013-08-24\\src");
String name="visit";
ClassLoader cl=new URLClassLoader(new URL[]{url});
Class className=cl.loadClass(name);
System.out.println("d------------------"+className);
System.out.println("cl----------------------"+cl);
action = Class.forName("visit").newInstance();
Method method=action.getClass().getMethod("showa");
method.invoke(action);