1.静态代理
package proxy;
public interface Greeting {
void sayHello(String name);
}
package proxy;
public class GreetingImpl implements Greeting {
@Override
public void sayHello(String name) {
System.out.println("Hello," + name);
}
}
package proxy;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GreetingProxy implements Greeting {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Greeting greetingObj;
public GreetingProxy(Greeting greetingObj) {
this.greetingObj = greetingObj;
}
@Override
public void sayHello(String name) {
logger.log(Level.INFO, "sayHello method starts...");
greetingObj.sayHello(name);
logger.log(Level.INFO, "sayHello method ends...");
}
}
2.动态代理
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogHandler implements InvocationHandler {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object originalObj;
public Object bind(Object obj){
this.originalObj = obj;
return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(),
originalObj.getClass().getInterfaces(),
this
);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
logger.log(Level.INFO,"method starts..."+method);
result = method.invoke(originalObj,args);
logger.log(Level.INFO,"method ends..."+method);
return result;
}
}
3.调用
package proxy;
public class Client {
public static void welcome(Greeting greeting,String name){
greeting.sayHello(name);
}
public static void main(String[] args) {
GreetingImpl greeting = new GreetingImpl();
welcome(greeting,"张三");
System.out.println("-----------------------------");
//使用代理
GreetingProxy greetingProxy = new GreetingProxy(greeting);
welcome(greetingProxy,"李四");
//动态代理
Greeting handler = (Greeting)new LogHandler().bind(greeting);
handler.sayHello("王五");
}
}