51_52 creates and calls the dynamic class instance object, 51_52 instance
Package com. itcast. day3; 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;/** three ways to get proxy objects ** 1. Intuitive type * 2. Anonymous internal type * 3. One-Step bytecode (recommended) */public class ProxyTest {public static void main (String [] args) throws Exception {// obtain the byte code of the Proxy Class class clazzProxy1 = Proxy. getProxyClass (Collection. class. getClassLoader (), Collection. class); // clazzProxy1.newInstance (); // you cannot do this, because the newInstance calls the construction method without parameters/** 1. The most intuitive way to create a proxy object *** // 01. obtain the parameter constructor System. out. println ("begin create instance"); Constructor constructor = clazzProxy1.getConstructor (InvocationHandler. class); // there must be an InvocationHandler instance for newInstance, but InvocationHandler is an interface, so this class InvocationHandlerImpl_1 implements InvocationHandler {@ Override public Object invoke (Object proxy, Method method, Method, object [] args) throws Throwable {// TODO Auto-generated method stub return null ;}// 02. obtain the instance object Collection proxy1 = (Collection) constructor. newInstance (new InvocationHandlerImpl_1 (); System. out. println (proxy1.toString (); // proxy1.clear (); // No Return Value Function // proxy1.size (); // return value function -- Null Pointer -- no target class/** 2. Use an anonymous internal class to get the proxy class Object ***/Collection proxy2 = (Collection) constructor. newInstance (new InvocationHandler () {@ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {return null ;}}); /** 3. Get the Proxy class object in one step. ** the above bytecode is not used, but the static method of Proxy is used in one step. **/Collection proxy3 = (Collection) Proxy. newProxyInstance (Collection. class. getClassLoader (), new Class [] {Collection. class}, new InvocationHandler () {ArrayList target = new ArrayList (); @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {long beginTime = System. currentTimeMillis (); Object reVal = method. invoke (target, args); long endTime = System. currentTimeMillis (); System. out. println (method. getName () + "running" + (endTime-beginTime); return reVal ;}}); proxy3.add ("123"); proxy3.add ("456 "); proxy3.size ();}}