Proxy.newProxyInstance() of dynamic proxy

package com.mango.demo;


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


import org.junit.Test;
/**
 * Dynamic proxy: At runtime, dynamically create a set of implementation class objects of the specified interface.
 * @author John
 *
 */


public class demo1 {
	@Test
	public void fun1(){
		
		ClassLoader loader = this.getClass().getClassLoader();
		InvocationHandler h = new InvocationHandler() {
			/**
			 * invoke() method:
			 * invoke is invoked when a method in the interface implemented by the proxy object is invoked.
			 * Parameters:
			 * 1.Object proxy: The current object, that is, the proxy object. That is to say whose method is being called
			 * 2.Method method: the currently called method
			 * 3.Object[] args: the actual parameters of the method
			 */
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				System.out.println("execute");
				// TODO Auto-generated method stub
				return null;
			}
		};
		/**
		 * Method function: Dynamically creates the implementation classes of all the specified interfaces in the interface array
		 * That is to say, the method dynamically generates a class that implements the A and B interfaces, and then creates this class
		 * Parameters:
		 * 1.ClassLoader:
		 * A class needs to be generated, this class also needs to be loaded into the method area, who will load it, of course ClassLoader
		 * 2.Class[] interface:
		 * Interfaces to implement
		 * 3.InvocationHandler:
		 * it is the call handler
		 */
		Object object = Proxy.newProxyInstance(loader, new Class[]{A.class,B.class}, h);
		/**
		 * The methods in all interfaces implemented by the proxy object, the content is to call the invoke() method of InvocationHandler
		 */
		A a = (A)object;
		a.a();
		/**
		 * a: Object proxy parameter of the invoke method
		 * aa: Method method parameter of the invoke method
		 * "hello" and 123: Object[] args parameter of invoke method
		 * result: return to invoke
		 */
		Object result = a.aa("hello", 123); //Not executed
	}
}
interface A {
	public void a();
	/**
	 * aa: Method method parameter of the invoke method
	 * @param s the Object[] args parameter of the invoke method
	 * @for me    
	 * @return Object : return to use invoke
	 */
	public Object aa(String s, int i);
}
interface B {
	public void b();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325816640&siteId=291194637