手写动态代理
MyInvocationHandler:
package com.lipengyu.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.lipengyu.service.Person;
public class MyInvocationHandler implements InvocationHandler {
private Person target;
public MyInvocationHandler(Person target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
wash();
Object value = method.invoke(target, args);
return value;
}
private void wash() {
System.out.println("洗手..");
}
}
ProxyFactory :
package com.lipengyu.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import com.lipengyu.service.Person;
public class ProxyFactory {
public static Person build(Class clazz) throws Exception {
Person person = (Person)clazz.newInstance();
InvocationHandler invocationHandler = new MyInvocationHandler(person);
return (Person) Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(),invocationHandler);
}
}
LiPengyu:
package com.lipengyu.service;
public class LiPengyu implements Person {
@Override
public void eat() {
System.out.println("我吃饭了....");
}
}
Person :
package com.lipengyu.service;
public interface Person {
void eat();
}
TestMain :
package com.lipengyu.util;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lipengyu.com.lipengyu.util.ProxyFactory;
import com.lipengyu.service.Person;
import com.lipengyu.service.LiPengyu;
import sun.misc.ProxyGenerator;
public class TestMain {
public static void main(String[] args) throws Exception {
Person person = ProxyFactory.build(LiPengyu.class);
person.eat();
createProxyClassFile(person.getClass());
}
private static void createProxyClassFile(Class c) {
byte[] data = ProxyGenerator.generateProxyClass("$Proxy()", new Class[]{c});
try {
FileOutputStream fileOutputStream = new FileOutputStream("$Proxy0.class");
fileOutputStream.write(data);
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}