package com.mypro.java;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//面向切面编程:AOP
interface Human{
void info();
void fly();
}
class SuperMan implements Human{
@Override
public void info(){
System.out.println(“我是超人!我怕谁!”);
}
@Override
public void fly() {
System.out.println("I can fly!");
}
}
class HumanUtil{
public void method1(){
System.out.println(“===方法一===”);
}
public void method2(){
System.out.println(“===方法二===”);
}
}
class MyInvocationHandler implements InvocationHandler{
Object obj;//被代理类对象的声明
public void setObject(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
HumanUtil h = new HumanUtil();
h.method1();
Object returnVal = method.invoke(obj, args);
h.method2();
return returnVal;
}
}
//创建一个动态的代理类
class MyProxy{
public static Object getProxyIntance(Object obj){
MyInvocationHandler handler = new MyInvocationHandler();
handler.setObject(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(), handler);
}
}
public class TestAOP{
public static void main(String[] args){
SuperMan man = new SuperMan();//创建一个代理类的对象
Object obj = MyProxy.getProxyIntance(man);//返回一个被代理类的对象
Human hu = (Human)obj;//强转为接口的类型
hu.info();//通过代理类调用重写的抽象方法
hu.fly();//通过代理类调用重写的抽象方法
/**
* ===方法一===
我是超人!我怕谁!
===方法二===
===方法一===
I can fly!
===方法二===
*/
/**
* 分析一下,为什么“方法一”、“方法二”显示两遍,因为一旦调用接口里面的方法,就换转到调用invoke方法
*/
}
}