Static agent
package com.staticProxy;
public interface Person {
public void eat();
}
Copy the code
package com.staticProxy;
public class Teacher implements Person{
@Override
public void eat(){
System.out.println("Teachers love to eat, too."); }}Copy the code
package com.staticProxy;
public class staticProxy implements Person{
private Teacher teacher;
public staticProxy(Teacher teacher){
this.teacher = teacher;
}
@Override
public void eat() {
System.out.println("Proxy mode"); teacher.eat(); }}Copy the code
package com.staticProxy;
public class test{ public static void main(String[] args) { Teacher teacher = new Teacher(); staticProxy staticProxy = new staticProxy(teacher); staticProxy.eat(); }}Copy the code
Dynamic proxies require reflection, borrowed from AOP
package com.dynamicProxy;
public interface Phone {
public String salePhone();
}
Copy the code
package com.dynamicProxy;
public class Apple implements Phone {
@Override
public String salePhone() {
return "Selling iphones."; }}Copy the code
package com.dynamicProxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class MyInvocationHandler implements InvocationHandler { private Object target; // Return the proxy Object publicbind(Object Object){// Save the delegate Object this.target = Object;return Proxy.newProxyInstance(
MyInvocationHandler.class.getClassLoader(),
target.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Proxy mode");
returnmethod.invoke(target,args); }}Copy the code
package com.dynamicProxy; Public class Test {public static void main(String[] args) {//1, Apple Apple = new Apple(); MyInvocationHandler handler = new MyInvocationHandler(); Phone phoneProxy = (Phone) handler.bind(apple); System.out.println(phoneProxy.salePhone()); }}Copy the code
Interviewer asks: How to do non-intrusive enhancement methods? A: Agency. It must be a dynamic proxy. Similar to aspect programming, non-intrusive enhancements to one or more methods can be accomplished using dynamic proxies.