1. Schnittstelle Human.java
public interface Human { void say(); }
2. Menschliche Implementierungsklasse
public class Person implements Human { @Override public void say() { System.out.println("haha"); } }
3. Verarbeitungsklasse
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. Verwenden Sie
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(); } }
5. Geben Sie das Ergebnis aus
before haha after