动态代理方式有好几种:一种一种来吧
第一种 spring Aop 见博客中找
第二种 jdk自身的,
=================================================================================================
==
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class PersonInvoke implements InvocationHandler {
public Object targetObj ;
public Object newProxy(Object targetObj){
this.targetObj = targetObj;
return Proxy.newProxyInstance(targetObj.getClass().getClassLoader(),
targetObj.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
checkSecurity();
Object result = null;
try{
result = method.invoke(this.targetObj, args);
}catch(Exception e ){
e.printStackTrace();
}
return result;
}
public void checkSecurity(){
System.out.println("-------checkSecurity Successfully!!!--------");
}
}
==
public interface Person {
public void sayHello();
}
==
public class PersonImpl implements Person {
@Override
public void sayHello() {
System.out.println("Hello Proxy");
}
}
==
public class Main {
public static void main(String[] args) {
PersonInvoke hander = new PersonInvoke();
Person proxy = (Person) hander.newProxy(new PersonImpl());
proxy.sayHello();
}
}