Java动态代办机制的涌现,使得 Java 开发人员不必手工编写代办类,只需简朴地指定一组接口及托付类对象,便能动态地取得代办类。(引荐:java视频教程)
代办类会担任将一切的要领挪用分配到托付对象上反射实行,在分配实行的过程当中,开发人员还能够按需调解托付类对象及其功用,这是一套异常天真有弹性的代办框架。下面我们入手下手动态代办的进修。
动态代办的扼要申明
在java的动态代办机制中,有两个主要的类或接口,一个是 InvocationHandler(Interface)、另一个则是 Proxy(Class)。
一、 InvocationHandler(interface)的形貌:
InvocationHandler is the interface implemented by the invocation handler of a proxy instance. Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.
每一个动态代办类都必须要完成InvocationHandler这个接口,而且每一个代办类的实例都关联到了一个handler,当我们经由过程代办对象挪用 一个要领的时刻,这个要领的挪用就会被转发为由InvocationHandler这个接口的 invoke 要领来举行挪用。我们来看看InvocationHandler这个接口的唯一一个要领 invoke 要领:
Object invoke(Object proxy, Method method, Object[] args) throws Throwable
这个要领吸收三个参数和返回一个Object范例,它们离别代表的意义以下:
proxy: 指代我们所代办的谁人实在对象
method: 指代的是我们所要挪用实在对象的要领的Method对象
args: 指代的是挪用实在对象某个要领时接收的参数
返回的Object是指实在对象要领的返回范例,以上会在接下来的例子中加以深切明白。
the value to return from the method invocation on the proxy instance.
二、 Proxy(Class)的形貌:
Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
Proxy这个类的作用就是用来动态建立一个代办对象。我们常常运用的是newProxyInstance这个要领:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
参数的明白:
// 一个ClassLoader对象,定义了由哪一个ClassLoader对象来对生成的代办对象举行加载 loader - the class loader to define the proxy class // 一个Interface对象的数组,示意的是我将要给我须要代办的对象供应一组什么接口 interfaces - the list of interfaces for the proxy class to implement // 一个InvocationHandler对象,示意的是当我这个动态代办对象在挪用要领的时刻,会关联到哪一个InvocationHandler对象上 h - the invocation handler to dispatch method invocations to
返回效果的明白: 一个代办对象的实例
a proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and that implements the specified interfaces
简朴的Java代办
我们建立一个Java项目用于对动态代办的测试与明白,项目构造以下:
一、 先定义一个接口Interface,增加两个要领。
package com.huhx.proxy; public interface Interface { void getMyName(); String getNameById(String id); }
二、 定义一个实在的完成上述接口的类,RealObject:
package com.huhx.proxy; public class RealObject implements Interface { @Override public void getMyName() { System.out.println("my name is huhx"); } @Override public String getNameById(String id) { System.out.println("argument id: " + id); return "huhx"; } }
三、 定义一个代办对象,也完成了上述的Interface接口:
package com.huhx.proxy; public class SimpleProxy implements Interface { private Interface proxied; public SimpleProxy(Interface proxied) { this.proxied = proxied; } @Override public void getMyName() { System.out.println("proxy getmyname"); proxied.getMyName(); } @Override public String getNameById(String id) { System.out.println("proxy getnamebyid"); return proxied.getNameById(id); } }
四、 SimpleMain在Main要领中,测试上述的效果:
package com.huhx.proxy; public class SimpleMain { private static void consume(Interface iface) { iface.getMyName(); String name = iface.getNameById("1"); System.out.println("name: " + name); } public static void main(String[] args) { consume(new RealObject()); System.out.println("========================================================"); consume(new SimpleProxy(new RealObject())); } }
五、 运转的效果以下:
my name is huhx argument id: 1 name: huhx ======================================================== proxy getmyname my name is huhx proxy getnamebyid argument id: 1 name: huhx
Java的动态代办
完成了上述简朴的Java代办,如今我们入手下手进修Java的动态代办,它比代办的头脑更向前一步,由于它能够动态地建立代办并动态的处置惩罚对所代办要领的挪用。在动态代办上所做的一切挪用都会被重定向到单一的挪用处置惩罚器上,它的事情是展现挪用的范例并肯定响应的对策。下面我们经由过程案例来加深Java动态代办的明白:
一、 建立一个继续了InvocationHandler的处置惩罚器:DynamicProxyHandler
package com.huhx.dynamicproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Arrays; public class DynamicProxyHandler implements InvocationHandler { private Object proxied; public DynamicProxyHandler(Object proxied) { System.out.println("dynamic proxy handler constuctor: " + proxied.getClass()); this.proxied = proxied; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("dynamic proxy name: " + proxy.getClass()); System.out.println("method: " + method.getName()); System.out.println("args: " + Arrays.toString(args)); Object invokeObject = method.invoke(proxied, args); if (invokeObject != null) { System.out.println("invoke object: " + invokeObject.getClass()); } else { System.out.println("invoke object is null"); } return invokeObject; } }
二、 我们写一个测试的Main要领,DynamicProxyMain:
package com.huhx.dynamicproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import com.huhx.proxy.Interface; import com.huhx.proxy.RealObject; public class DynamicProxyMain { public static void consumer(Interface iface) { iface.getMyName(); String name = iface.getNameById("1"); System.out.println("name: " + name); } public static void main(String[] args) throws Exception, SecurityException, Throwable { RealObject realObject = new RealObject(); consumer(realObject); System.out.println("=============================="); // 动态代办 ClassLoader classLoader = Interface.class.getClassLoader(); Class<?>[] interfaces = new Class[] { Interface.class }; InvocationHandler handler = new DynamicProxyHandler(realObject); Interface proxy = (Interface) Proxy.newProxyInstance(classLoader, interfaces, handler); System.out.println("in dynamicproxyMain proxy: " + proxy.getClass()); consumer(proxy); } }
三、 运转效果以下:
my name is huhx argument id: 1 name: huhx ============================== dynamic proxy handler constuctor: class com.huhx.proxy.RealObject in dynamicproxyMain proxy: class com.sun.proxy.$Proxy0 dynamic proxy name: class com.sun.proxy.$Proxy0 method: getMyName args: null my name is huhx invoke object is null dynamic proxy name: class com.sun.proxy.$Proxy0 method: getNameById args: [1] argument id: 1 invoke object: class java.lang.String name: huhx
从以上输出效果,我们能够得出以下结论:
与代办对象相干联的InvocationHandler,只要在代办对象挪用要领时,才会实行它的invoke要领
invoke的三个参数的明白:Object proxy是代办的对象, Method method是实在对象中挪用要领的Method类, Object[] args是实在对象中挪用要领的参数
Java动态代办的道理
一、 动态代办的症结代码就是Proxy.newProxyInstance(classLoader, interfaces, handler),我们跟进源代码看看:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { // handler不能为空 if (h == null) { throw new NullPointerException(); } final Class<?>[] intfs = interfaces.clone(); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkProxyAccess(Reflection.getCallerClass(), loader, intfs); } /* * Look up or generate the designated proxy class. */ // 经由过程loader和接口,获得代办的Class对象 Class<?> cl = getProxyClass0(loader, intfs); /* * Invoke its constructor with the designated invocation handler. */ try { final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) { // create proxy instance with doPrivilege as the proxy class may // implement non-public interfaces that requires a special permission return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return newInstance(cons, ih); } }); } else { // 建立代办对象的实例 return newInstance(cons, ih); } } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); } }
二、 我们看一下newInstance要领的源代码:
private static Object newInstance(Constructor<?> cons, InvocationHandler h) { try { return cons.newInstance(new Object[] {h} ); } catch (IllegalAccessException | InstantiationException e) { throw new InternalError(e.toString()); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw new InternalError(t.toString()); } } }
三、 当我们经由过程代办对象挪用 一个要领的时刻,这个要领的挪用就会被转发为由InvocationHandler这个接口的 invoke 要领来举行挪用。
表现这句话的代码,我在源码中没有找到,因而我在测试类的main要领中到场以下代码:
if (proxy instanceof Proxy) { InvocationHandler invocationHandler = Proxy.getInvocationHandler(proxy); invocationHandler.invoke(proxy, realObject.getClass().getMethod("getMyName"), null); System.out.println("--------------------------------------"); }
这段代码的输出效果以下,与上述中挪用代办对象中的getMyName要领输出是一样的,不知道Jvm底层是不是是如许推断的:
dynamic proxy handler constuctor: class com.huhx.proxy.RealObject dynamic proxy name: class com.sun.proxy.$Proxy0 method: getMyName args: null my name is huhx invoke object is null --------------------------------------
更多java学问请关注java基础教程栏目。
以上就是Java动态代办的道理的细致内容,更多请关注ki4网别的相干文章!