代理代码是:
1. public static Object newProxyInstance( Class inface) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
String rt ="\r\n";
String method="";
for(Method m:inface.getMethods()){
method +="public void "+m.getName()+"() {"+rt+
" long stime = System.currentTimeMillis();"+rt+
" System.out.println(\"汽车开始行驶\");"+rt+
" "+m.getName()+"();"+rt+
" long etime = System.currentTimeMillis();"+rt+
" System.out.println(\"汽车行驶时间为\"+(etime-stime)+\"毫秒\");"+rt+
"}";
}
String s=
"package com.Proxy;"+rt+
"public class $Proxy1 implements "+inface.getName()+" {"+rt+
" public $Proxy1("+inface.getName()+" m){"+rt+
" super();"+rt+
" this.m=m;"+rt+
"}"+rt+
"private "+inface.getName()+" m ;"+rt+
method+
"}";
String filename = System.getProperty("user.dir")+"/bin/com/Proxy/$Proxy1.java";
//String filename2 = System.getProperty("user.dir")+"/bin/com/Proxy/$Proxy1.class";
System.out.println(filename);
File file = new File(filename);
FileUtils.writeStringToFile(file,s);
//编译
//拿到编辑器
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
//文件管理者
StandardJavaFileManager m = c.getStandardFileManager(null, null, null);
//获取文件
Iterable u = m.getJavaFileObjects(filename);
//编译任务
CompilationTask t =c.getTask(null, m, null, null, null, u);
t.call();
m.close();
//load到内存
ClassLoader cl =ClassLoader.getSystemClassLoader();
Class cs =cl.loadClass("bin.com.Proxy");
Constructor ctr = cs.getDeclaredConstructor(inface);
System.out.println(cs.getName());
return ctr.newInstance(new Car());
}
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Moveable m=(Moveable) Proxy.newProxyInstance(Moveable.class);
m.move();
}
String filename = System.getProperty("user.dir")+"/bin/com/Proxy/$Proxy1.java";
Class cs =cl.loadClass("bin.com.Proxy");
感觉这两个路径有问题,求大神