OK,言归正传。
* 一个代理类,也实现了接口,是增强版的实现类
/**
* @description 代理模式 之 静态代理 -- StaticProxyInterface接口
* @description 一个接口
*/
public interface StaticProxyInterface {
public void queryInfo();
}
/**
* @description 代理模式 之 静态代理 -- StaticProxyImpl实现类
* @description StaticProxyImpl,在代理模式中,叫做委托类,包含业务逻辑
* @description 一个接口实现类
*/
public class StaticProxyImpl implements StaticProxyInterface{
public void queryInfo() {
System.out.println("代理模式 之 静态代理 -- StaticProxyImpl实现类 查看信息...");
}
}
/**
* @description 代理模式 之 静态代理 -- StaticProxy代理类
* @description StaticProxy,在代理模式中,叫做代理类,增强StaticProxyImpl实现类
* @description 一个代理类,也实现了接口,是增强版的实现类
*/
public class StaticProxy implements StaticProxyInterface{
private StaticProxyImpl staticProxyImpl;
public StaticProxy(StaticProxyImpl staticProxyImpl){
this.staticProxyImpl = staticProxyImpl;
}
public void queryInfo() {
// 事务处理之前,可以执行一段代码
System.out.println("事务处理之前...");
// 调用委托类的方法
staticProxyImpl.queryInfo();
// 事务处理之后,可以执行一段代码
System.out.println("事务处理之后...");
}
}
/**
* @description 代理模式 之 静态代理
* @description 测试类StaticProxyTest
* @description 什么是静态代理:静态代理指的是,由程序员创建或特定工具自动生成源代码,再对其进行编译。
* 在程序运行前,代理类的.class文件就已经存在了。
* @description 静态代理组成要素:
* 1,一个接口
* 2,一个接口实现类
* 3,一个代理类,也实现接口,是增强版的接口实现类
*/
public class StaticProxyTest {
public static void main(String[] args){
StaticProxyImpl staticProxyImpl = new StaticProxyImpl();
StaticProxy staticProxy = new StaticProxy(staticProxyImpl);
staticProxy.queryInfo();
}
/*
* 静态代理的一个缺点就是:我们需要为每一个接口生成一个代理类,也就是一个接口必然要对应一个代理类。这样
* 必然会生成很多的代理类,并且这些代理类的代码有很多重复的部分。解决这一问题,最好的办法就是通过一个代理类
* 完成全部的代理功能,此时就要使用动态代理。
*/
}
/**
* @description 代理模式 之 JDK的动态代理 -- DynamicProxyInterface接口
* @description 一个接口
*/
public interface DynamicProxyInterface {
public void queryInfo();
}
/**
* @description 代理模式 之 JDK的动态代理 -- DynamicProxyImpl实现类
* @description DynamicProxyImpl,在代理模式中,叫做委托类,包含业务逻辑
* @description 一个接口实现类
*/
public class DynamicProxyImpl implements DynamicProxyInterface {
public void queryInfo() {
// TODO Auto-generated method stub
System.out.println("代理模式 之 JDK的动态代理 -- DynamicProxyImpl实现类 查看信息...");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @description 代理模式 之 JDK的动态代理 -- DynamicProxy代理类
* @description DynamicProxy,在代理模式中,叫做代理类,增强DynamicProxyImpl实现类
* @description 一个代理类,实现了InvocationHandler接口
* @description JDK的动态代理 与 静态代理的区别就在这个代理类,静态代理类直接实现接口,而JDK的动态代理类不
* 直接实现具体的接口,而是实现了JDK提供的InvocationHandler接口。
*/
public class DynamicProxy implements InvocationHandler {
// 目标实现类,也就是某个接口的实现类,这里的target_interface_implements,可以看做是一种抽象
private Object target_interface_implements;
// 带参数构造方法,把目标实现类的对象作为参数传递进去,这里不是覆盖具体某个实现类的构造方法,而是抽象出来一个方法
public Object dynamicBindImplToProxyClass(Object target_interface_implements){
this.target_interface_implements = target_interface_implements;
// 取得代理对象
return Proxy.newProxyInstance(target_interface_implements.getClass().getClassLoader(),
target_interface_implements.getClass().getInterfaces(), this);
// JDK的动态代理依赖具体的接口,需要绑定接口,如果一个类没有实现接口,则不能使用JDK的动态代理
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object result = null;
// 事务处理之前,可以执行一段代码
System.out.println("事务处理之前...");
// 执行方法
result = method.invoke(target_interface_implements, args);
// 事务处理之后,可以执行一段代码
System.out.println("事务处理之后...");
return result;
}
}
package com.ebank.action;
/**
* @description 代理模式 之 JDK的动态代理
* @description 测试类DynamicProxyTest
* @description 动态代理指的是,在程序运行时,运用反射机制动态生成源代码,再对其进行编译。
* @description JDK的动态代理组成要素:
* 1,一个接口
* 2,一个接口实现类
* 3,一个代理类,实现了InvocationHandler接口
*/
public class DynamicProxyTest {
public static void main(String[] args){
DynamicProxy dynamicProxy = new DynamicProxy();
DynamicProxyInterface dynamicProxyForImpl = (DynamicProxyInterface) dynamicProxy.dynamicBindImplToProxyClass(new DynamicProxyImpl());
dynamicProxyForImpl.queryInfo();
}
/*
* JDK的动态代理依靠具体的接口,如果有些类并没有实现,则不能使用JDK的动态代理,这时候就需要
* 使用CGLIB的动态代理
* // JDK的动态代理的关键是InvocationHandler接口
*/
}
package java.lang.reflect;
public interface InvocationHandler {
/**
* Processes a method invocation on a proxy instance and returns the result. This method will be invoked on an invocation
* handler when a method is invoked on a proxy instance that it is associated with.
* Processes : 处理,加工,审核
* @param proxy--the proxy instance that the method was invoked on
*
* @param method--the Method instance corresponding to the interface method invoked on the proxy instance. The declaring
* class of the Method object will be the interface that the method was declared in, which may be a
* superinterface of the proxy interface that the proxy class inherits the method through.
*
* @param args--an array of objects containing the values of the arguments passed in the method invocation on the proxy
* instance, or null if interface method takes no arguments.Arguments of primitive types are wrapped in instances of the
* appropriate primitive wrapper class, such as Integer or Boolean.
* primitive : 简单的,这里个人理解为基本的,primitive type 意为基本数据类型
* @return the value to return from the method invocation on the proxy instance. If the declared return type of the interface
* method is a primitive type, then the value returned by this method must be an instance of the corresponding primitive
* wrapper class; otherwise, it must be a type assignable to the declared return type. If the value returned by this method is
* null and the interface method's return type is primitive, then a NullPointerException will be
* thrown by the method invocation on the proxy instance. If the value returned by this method is otherwise not compatible with
* the interface method's declared return type as described above, a ClassCastException will be thrown by the method
* invocation on the proxy instance.
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
/**
* @description 代理模式 之 CGLIB的动态代理 -- CglibDynamicProxyImpl类
* @description CglibDynamicProxyImpl,在代理模式中,叫做委托类,包含业务逻辑
* @description 一个没有实现接口的类
*/
public class CglibDynamicProxyImpl {
public void queryInfo() {
// TODO Auto-generated method stub
System.out.println("代理模式 之 CGLIB的动态代理 -- CglibDynamicProxyImpl类 查看信息...");
}
}
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* @description 代理模式 之 CGLIB的动态代理 -- CglibDynamicProxy代理类
* @description CglibDynamicProxy,在代理模式中,叫做代理类,增强DynamicProxyImpl实现类
* @description 一个代理类,实现了MethodInterceptor接口
* @description CGLIB的动态代理 与 静态代理的区别就在这个代理类,静态代理类直接实现接口,而CGLIB的动态代理类不
* 直接实现具体的接口,而是实现了MethodInterceptor接口。
*/
public class CglibDynamicProxy implements MethodInterceptor {
// 目标实现类,也就是某个接口的实现类,这里的target_interface_implements,可以看做是一种抽象
private Object target_class;
// 创建代理对象
public Object getInstance(Object target_class){
this.target_class = target_class;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target_class.getClass());
// 回调方法
enhancer.setCallback(this);
// 创建代理对象
return enhancer.create();
}
// 回调方法
public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy proxy) throws Throwable {
// 事务处理之前,可以执行一段代码
System.out.println("事务处理之前...");
// 执行方法
proxy.invokeSuper(arg0, arg2);
// 事务处理之后,可以执行一段代码
System.out.println("事务处理之后...");
return null;
}
}
/**
* @description 代理模式 之 CGLIB的动态代理
* @description 测试类CglibDynamicProxyTest
* @description 动态代理指的是,在程序运行时,运用反射机制动态生成源代码,再对其进行编译。
* @description CGLIB的动态代理组成要素:
* 1,一个类
* 2,一个代理类,实现了MethodInterceptor接口
*/
public class CglibDynamicProxyTest {
public static void main(String[] args){
CglibDynamicProxy cglibDynamicProxy = new CglibDynamicProxy();
CglibDynamicProxyImpl cglibDynamicProxyImpl = (CglibDynamicProxyImpl) cglibDynamicProxy.getInstance(new CglibDynamicProxyImpl());
cglibDynamicProxyImpl.queryInfo();
}
// CGLIB的动态代理的关键是MethodInterceptor接口
}
Exception in thread "main" java.lang.IllegalArgumentException: Cannot subclass final class class com.yangcq.CglibDynamicProxyImpl
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:285)
at com.ebank.action.CglibDynamicProxy.getInstance(CglibDynamicProxy.java:24)
at com.ebank.action.CglibDynamicProxyTest.main(CglibDynamicProxyTest.java:14)
package net.sf.cglib.proxy;
import java.lang.reflect.Method;
public abstract interface MethodInterceptor extends Callback{
public abstract Object intercept(Object paramObject, Method paramMethod, Object[] paramArrayOfObject,
MethodProxy paramMethodProxy) throws Throwable;
}
package java.lang.reflect;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import sun.misc.ProxyGenerator;
public class Proxy implements java.io.Serializable {
private static final long serialVersionUID = -2222568056686623797L;
private final static String proxyClassNamePrefix = "$Proxy";
private final static Class[] constructorParams = { InvocationHandler.class };
private static Map loaderToCache = new WeakHashMap();
private static Object pendingGenerationMarker = new Object();
private static long nextUniqueNumber = 0;
private static Object nextUniqueNumberLock = new Object();
private static Map proxyClasses = Collections.synchronizedMap(new WeakHashMap());
protected InvocationHandler h;
// 私有构造函数,不允许程序员通过构造函数来实例化Proxy,生成Proxy的实例,需要调用newProxyInstance方法
private Proxy() {
}
// 受保护的构造函数,这个函数也不允许程序员直接调用
protected Proxy(InvocationHandler h) {
this.h = h;
}
public static Class> getProxyClass(ClassLoader loader, Class>... interfaces) throws IllegalArgumentException{
// 这行代码,可以说明,在Class类文件的数据结构中,接口interfaces占用2个字节,最大值65535
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
Class proxyClass = null;
String[] interfaceNames = new String[interfaces.length];
// Set是无序,不可重复的集合
Set interfaceSet = new HashSet();
for (int i = 0; i < interfaces.length; i++) {
String interfaceName = interfaces[i].getName();
Class interfaceClass = null;
try {
// 通过接口名称和类加载器,获得接口实现类
interfaceClass = Class.forName(interfaceName, false, loader);
}
catch (ClassNotFoundException e) {
}
if (interfaceClass != interfaces[i]) {
throw new IllegalArgumentException(interfaces[i] + " is not visible from class loader");
}
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(interfaceClass.getName() + " is not an interface");
}
if (interfaceSet.contains(interfaceClass)) {
throw new IllegalArgumentException("repeated interface: " + interfaceClass.getName());
}
interfaceSet.add(interfaceClass);
interfaceNames[i] = interfaceName;
}
Object key = Arrays.asList(interfaceNames);
Map cache;
synchronized (loaderToCache) {
cache = (Map) loaderToCache.get(loader);
if (cache == null) {
cache = new HashMap();
loaderToCache.put(loader, cache);
}
}
synchronized (cache) {
do {
Object value = cache.get(key);
if (value instanceof Reference) {
proxyClass = (Class) ((Reference) value).get();
}
if (proxyClass != null) {
return proxyClass;
}
else if (value == pendingGenerationMarker) {
try {
cache.wait();
}
catch (InterruptedException e) {
}
continue;
}
else {
cache.put(key, pendingGenerationMarker);
break;
}
} while (true);
}
try {
String proxyPkg = null;
for (int i = 0; i < interfaces.length; i++) {
int flags = interfaces[i].getModifiers();
if (!Modifier.isPublic(flags)) {
String name = interfaces[i].getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
}
else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException("non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
proxyPkg = "";
}
{
long num;
synchronized (nextUniqueNumberLock) {
num = nextUniqueNumber++;
}
String proxyName = proxyPkg + proxyClassNamePrefix + num;
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces);
try {
proxyClass = defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
}
catch (ClassFormatError e) {
throw new IllegalArgumentException(e.toString());
}
}
proxyClasses.put(proxyClass, null);
}
finally {
synchronized (cache) {
if (proxyClass != null) {
cache.put(key, new WeakReference(proxyClass));
}
else {
cache.remove(key);
}
cache.notifyAll();
}
}
return proxyClass;
}
public static Object newProxyInstance(ClassLoader loader, Class>[] interfaces, InvocationHandler h)
throws IllegalArgumentException{
if (h == null) {
throw new NullPointerException();
}
// 获得代理类,需要传递2个参数,类加载器和接口
Class cl = getProxyClass(loader, interfaces);
try {
// 获得代理类的构造函数
Constructor cons = cl.getConstructor(constructorParams);
// 通过构造函数,生成实例对象
return (Object) cons.newInstance(new Object[] { h });
}
catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
}
catch (IllegalAccessException e) {
throw new InternalError(e.toString());
}
catch (InstantiationException e) {
throw new InternalError(e.toString());
}
catch (InvocationTargetException e) {
throw new InternalError(e.toString());
}
}
public static boolean isProxyClass(Class> cl) {
if (cl == null) {
throw new NullPointerException();
}
return proxyClasses.containsKey(cl);
}
public static InvocationHandler getInvocationHandler(Object proxy) throws IllegalArgumentException{
if (!isProxyClass(proxy.getClass())) {
throw new IllegalArgumentException("not a proxy instance");
}
Proxy p = (Proxy) proxy;
return p.h;
}
private static native Class defineClass0(ClassLoader loader, String name, byte[] b, int off, int len);
}