必要条件
对象及对象的接口
public interface UserService {
void getname();
}
public class UserServiceImpl implements UserService {
public void getname() {
System.out.println("我叫tom");
}
}
然后代理实例
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class Aahandler implements InvocationHandler {
private Object target;
public Aahandler(Object target) {
this.target = target;
}
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
System.out.println("我的名字");
Object invoke=method.invoke(target,objects);
System.out.println("完毕");
return invoke;
}
}
测试
import org.junit.Test;
import java.lang.reflect.Proxy;
public class TEST {
@Test
public void test(){
UserService service=new UserServiceImpl();
Aahandler aahandler=new Aahandler(service);
service= (UserService) Proxy.newProxyInstance(service.getClass().getClassLoader(),service.getClass().getInterfaces(),aahandler);
service.getname();
}
}