java 高新技术【11.1】 动态代理类 InvocationHandler对象 (静态代理 与 动态代理 区别)


1,客户端 请求 代理(proxy),这时,把Invocationhandler 以参数的形式 传递给 代理(proxy)

2,客户端 在调用  代理(proxy)的其他方法,其他方法,也调用 (InvocationHandler)。

3,而 InvocationHandler   就执行,invoke方法,而这时 invoke 就可以调用目标程序,来完成 业务逻辑实现。

4,在 invocationHandler里面 有个 log方法,这里是作为一个对象,在这个对象里面  有实现的方法,来完成一些业务,正好是 spring的面向切面编程。

package com.itm.itcast;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyTest{

	/**
	 * @param args
	 * @throws Exception 
	 * @throws SecurityException 
	 */
	public static void main(String[] args) throws SecurityException, Exception {
		
		Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		System.out.println(clazzProxy1.getName());
		
		
		System.out.println("  以下  :创建动态类的实例对象及调用其方法 ");
		
		Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
		
		
		class MyInvocationHandler1 implements InvocationHandler{

			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// TODO Auto-generated method stub
				return null;
			}
			
		}
		
		Collection proxy1 = (Collection) constructor.newInstance(new MyInvocationHandler1());
		System.out.println(proxy1);
		// 下面两行代码在执行的时候   都会找 invoke的,而在invoke的方法里 返回的是 null,所以会报错。,。。
		proxy1.clear();
		proxy1.size();
		System.out.println("^^^^^^^^^^^");
		
		
		Collection proxy2 = (Collection)constructor.newInstance(new InvocationHandler(){

			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				
				return null;
			}
			
		});
		
		Collection proxy3 = (Collection)Proxy.newProxyInstance(
				Collection.class.getClassLoader(), 
				/*interfaces*/ 
				new Class[]{Collection.class},
				/*h*/
				new InvocationHandler(){
					// 若放到这里:size() 就会打印 三。
					/*(1)*/ArrayList target = new ArrayList();
					@Override
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						
						/*(2)*/ArrayList target = new ArrayList();
						long startTime = System.currentTimeMillis();
						Object retVal = method.invoke(target, args);
						long endTime = System.currentTimeMillis();
						System.out.println(method.getName() + " :runing time of " + (endTime - startTime));
						return  retVal;
					}
			
				}
				);
		// 每调用 一次 add方法  就会 找一次:InvocationHandler() 的  invoke 的方法。
		proxy3.add("zxx");
		proxy3.add("lhm");
		proxy3.add("kkkk");
		System.out.println(proxy3.size());
	}

}

以下方式 利用 动态代理:

package com.itm.proxy;



import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		final ArrayList target = new ArrayList();			
		Collection proxy3 = (Collection)getProxy(target,new MyAdvice());
		proxy3.add("aaa");
		proxy3.add("bbb");
		proxy3.add("ccc");
		System.out.println(proxy3.size());
		System.out.println(proxy3.getClass().getName());
	}

	private static Object getProxy(final Object target,final Advice advice) {
		Object proxy3 = Proxy.newProxyInstance(
				target.getClass().getClassLoader(),
				target.getClass().getInterfaces(),
				new InvocationHandler(){
				
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						advice.beforeMethod(method);
						Object retVal = method.invoke(target, args);
						advice.afterMethod(method);
						return retVal;						
						
					}
				}
				);
		return proxy3;
	}

}

接口:

import java.lang.reflect.Method;

public interface Advice {
	void beforeMethod(Method method);
	void afterMethod(Method method);
}

实现接口以及相应的业务逻辑:

import java.lang.reflect.Method;

public class MyAdvice implements Advice {
	long beginTime = 0;
	public void afterMethod(Method method) {
		// TODO Auto-generated method stub
		System.out.println("方法后");		
		long endTime = System.currentTimeMillis();
		System.out.println(method.getName() + " running time of " + (endTime - beginTime));

	}

	public void beforeMethod(Method method) {
		// TODO Auto-generated method stub
		System.out.println("方法前");
		beginTime = System.currentTimeMillis();
	}

}

运行结果:


方法前
方法后
add running time of 0
方法前
方法后
add running time of 0
方法前
方法后
add running time of 0
方法前
方法后
size running time of 0
3
$Proxy0




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
动态创建动态代理Java中非常重要的概念,下面分别进行介绍: 1. 动态创建 Java中可以使用反射机制动态创建,具体步骤如下: - 创建一个ClassWriter对象,用于生成的二进制字节码; - 调用ClassWriter的visit方法,生成的头部信息; - 调用visitField方法,生成的成员变量; - 调用visitMethod方法,生成的方法; - 调用visitEnd方法,生成的尾部信息; - 调用ClassLoader的defineClass方法,将生成的字节码转换为Class对象。 下面是一个简单的示例代码: ```java import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public class DynamicClassCreator { public static void main(String[] args) throws Exception { // 创建ClassWriter对象 ClassWriter cw = new ClassWriter(0); // 生成的头部信息 cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "DynamicClass", null, "java/lang/Object", null); // 生成的成员变量 cw.visitField(Opcodes.ACC_PRIVATE, "name", "Ljava/lang/String;", null, null).visitEnd(); // 生成的构造方法 MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); // 生成的方法 mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "sayHello", "()V", null, null); mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("Hello, world!"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(2, 1); mv.visitEnd(); // 生成的尾部信息 cw.visitEnd(); // 将生成的字节码转换为Class对象 byte[] code = cw.toByteArray(); Class<?> clazz = new MyClassLoader().defineClass("DynamicClass", code); // 创建对象并调用方法 Object obj = clazz.newInstance(); clazz.getMethod("sayHello").invoke(obj); } } class MyClassLoader extends ClassLoader { public Class<?> defineClass(String name, byte[] code) { return defineClass(name, code, 0, code.length); } } ``` 2. 动态代理 Java中可以使用动态代理机制生成代理,代理可以在不改变原有代码的情况下增加一些额外的功能,具体步骤如下: - 创建一个InvocationHandler对象,用于处理代理的方法调用; - 调用Proxy的newProxyInstance方法,生成代理的实例。 下面是一个简单的示例代码: ```java import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicProxy { public static void main(String[] args) { // 创建InvocationHandler对象 InvocationHandler handler = new MyInvocationHandler(); // 创建代理的实例 MyInterface proxy = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(), new Class<?>[] { MyInterface.class }, handler); // 调用代理的方法 proxy.sayHello(); } } interface MyInterface { void sayHello(); } class MyInvocationHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method " + method.getName()); Object result = method.invoke(new MyClass(), args); System.out.println("After method " + method.getName()); return result; } } class MyClass implements MyInterface { public void sayHello() { System.out.println("Hello, world!"); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值