Java 动态代理

 

public interface B {
	public void refA();
}

 

public class A implements B{

	public void refA() {
		System.out.println("This A");
	}
}

 

public class C implements B{

	@Override
	public void refA() {
		System.out.println("This C");
	}
}

 

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MapperProxy implements InvocationHandler, Serializable {

	private Object obj;

	<T> MapperProxy(Object obj) {
		this.obj = obj;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println(" before calling " + method);
		System.out.println(method.getDeclaringClass());
		System.out.println(Object.class);
		
		method.invoke(obj, args);

		System.out.println(" after calling " + method);
		return null;
	}
}

 

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class ProxyTest {

	public static void main(String[] args) {
		try {
			ProxyTest p = new ProxyTest();

/*			B aa = p.proxyClass((Class<T>) Class.forName("com.navinfo.sys.test.A")
					.newInstance().getClass());*/
			
			B aa = p.proxyClass(B.class);
			aa.refA();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public <T> T proxyClass(Class<T> mapperInterface) {
		// java 动态代理
		ClassLoader classLoader = mapperInterface.getClassLoader();
		Class<?>[] interfaces = new Class[] { mapperInterface };

		for (int i = 0; i < interfaces.length; i++) {
			System.out.println("||" + interfaces[i]);
		}
		
		B a = new C();

		InvocationHandler proxy = new MapperProxy(a);
		return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy);
	}
}

 

latex-table

java动态代理类位于java.lang.reflect包下,一般主要涉及到以下两个类:

  1. Interface InvocationHandler:该接口中仅定义了一个方法Object:invoke(Object obj,Method method, Object[] args)。在实际使用时,第一个参数obj一般是指代理 类,method是被代理的方法,如上例中的request(),args为该方法的参数数组。 这个抽 象方法在代理类中动态实现。
  2. Proxy:该类即为动态代理类,作用类似于上例中的ProxySubject。
  3. Protected Proxy(InvocationHandler h):构造函数,估计用于给内部的h赋值。
  4. Static Class getProxyClass (ClassLoader loader, Class[] interfaces):获得一个 代理类,其中loader是类装载器,interfaces是真实类所拥有的全部接口的数组。
  5. Static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h):返回代理类的一个实例,返回后的代理类可以当作被代理类使用 (可使用被代理类的在Subject接口中声明过的方法)。

在使用动态代理类时,我们必须实现InvocationHandler接口,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值