1.介面Human.java
public interface Human { void say(); }
2.Human的實作類別 Person
public class Person implements Human { @Override public void say() { System.out.println("haha"); } }
3.處理類別
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class Hander implements InvocationHandler { private Object obj; public Hander(Object obj) { this.obj = obj; } public Hander() { } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); method.invoke(obj, args); System.out.println("after"); return null; } }
4. 使用結果import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Human i = (Human) Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), Person.class.getInterfaces(),
new Hander(new Person()));
i.say();
}
}