java-based Dynamic Proxy


package proxy; public interface human { public void run(); public void eat(); }

  Defined interfaces

 

 

 

 

To complete the definition of the interface class

package proxy;

public class teacher implements human{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("走");
	}

	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("吃");
	}

}

 

To complete the definition of the main function

Proxy Package; 

Import java.lang.reflect.InvocationHandler; 
Import the java.lang.reflect.Method; 
Import the java.lang.reflect.Proxy; 

Import org.junit.Test; 

public class Demo { 
	public static void main (String [] args ) { 
		Teacher Teacher teacher1 new new = (); 
		
		Human teacher2 = (Human) the Proxy.newProxyInstance (teacher.class.getClassLoader (), teacher.class.getInterfaces (), of InvocationHandler new new () { 

			
			execute proxy object / * invoke represented object args method the method of the method of the response parameter object * / 
			@Override 
			public Invoke object (object Proxy, method, method, object [] args) throws the Throwable { 
				System.out.println ( "before doing something"); 
				} 
				IF (method. getName (). equals ( "eat ")) {/ * * determination method /
					System.out.println ( "ran down the steps before eating"); 
				
				// method to perform target object        
				Object invokea = Method.invoke (new new Teacher (), args); 
				System.out.println ( "After doing something") ; 
				// Generated Method Stub the TODO Auto- 
				return invokea; 
			} 
		}); 
		
		
		teacher1.eat (); 
		teacher1.run (); 
		System.out.println ( "teacher 1 completed"); 
		teacher2.eat (); 
		teacher1.run (); 
		
	} 
}

  result

Eat
away
teachers complete 1
before doing something
ran down the steps before eating
eat
do something after
walking

 

Dynamic Proxy

  You can only cut into ways to change the class at runtime, without the need to pre-define it.

 

Guess you like

Origin www.cnblogs.com/hywhyme/p/11618895.html