一.代理模式在架构中有者广泛的用途。java中已经提供了动态代理类来方便大家使用。下面是应用的一个例子。
1.接口类 UseJavaProxy.java
package test;
public interface UseJavaProxy {
public void theCloseMethod();
}
2.实现测试类 UseJavaProxyImpl.java
package test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class UseJavaProxyImpl implements UseJavaProxy {
public void theCloseMethod() {
System.out.println("the close method is in process");
}
public static void main(String[] args) {
//得到接口声明的方法
UseJavaProxy useJavaProxy = (UseJavaProxy) Proxy.newProxyInstance(UseJavaProxyImpl.class.getClassLoader(),
UseJavaProxyImpl.class.getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before--------"+method.getName());
//执行真正的方法
method.invoke(new UseJavaProxyImpl(),args);
System.out.println("after--------"+method.getName() + "\n");
return null;
}
});
//测试
useJavaProxy.theCloseMethod();
}
}
二.当代理和java的annoutation结合结合使用的时候,可以在某些地方取代xml等配置,方便我们的编程。下面是上面例子的进一步加深,结合annotation
1.annotation类 Exetable.java
package test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//加载在VM中,在运行时进行映射
@Retention(RetentionPolicy.RUNTIME)
//限定此annotation只能标示方法
@Target(ElementType.METHOD)
public @interface Exetable {
String value();
}
2. 接口类 UseJavaProxy.java
package test;
public interface UseJavaProxy {
@Exetable("true")
public void theCloseMethod();
}
3. 实现测试类 UseJavaProxyImpl.java
package test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class UseJavaProxyImpl implements UseJavaProxy {
public void theCloseMethod() {
System.out.println("the close method is in process");
}
public static void main(String[] args) {
//得到接口声明的方法
UseJavaProxy useJavaProxy = (UseJavaProxy) Proxy.newProxyInstance(UseJavaProxyImpl.class.getClassLoader(),
UseJavaProxyImpl.class.getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before--------"+method.getName());
//执行真正的方法
if(method.isAnnotationPresent(Exetable.class)) {
//当然我们的 Exetable 完全可以不定义 String value(); 语句
//这样我们简单的判断一下执行方法是否被标记修饰就可以了,有的话,我们可以
//得到更多的信息,来分支判断,如我们完全可以把 标志值作为判断条件来决定
//是否执行一个方法,以及执行该方法的前后要做什么
String annotationValue = method.getAnnotation(Exetable.class).value();
System.out.println("the annotation value is " + annotationValue);
method.invoke(new UseJavaProxyImpl(),args);
}
System.out.println("after--------"+method.getName() + "\n");
return null;
}
});
//测试
useJavaProxy.theCloseMethod();
}
}