We need to master the use of two classes:
-
public interface InvocationHandler
InvocationHandler
Call Interface handler is implemented through a proxy instance.Proxy access can be achieved through real role invoke method.
Agent class object generation by proxy, the processor must designate corresponding object.
-
invoke
Object invoke(Object proxy,方法 method,Object[] args)throws Throwable
Processing method invocation on the proxy instance, and returns the result. When you call a method on a proxy instance associated with it, the method invokes this method on invocation handler.- parameter
-
proxy
- Method Acting instance, call -
Interface method invocation to the corresponding
method
proxy instance方法
instance. Declare class方法
object interface method declaration, this could be a super-interface agent interface proxy class inherits the method. -
args
- an array containing values of the object argument on the method by calling the proxy instance, ornull
if the interface method takes no parameters. Original type argument is wrapped in the original packaging suitable example of suchjava.lang.Integer
orjava.lang.Boolean
. - Code:
- star
. 1 Package org.west.demo; 2 . 3 public interface Star { . 4 // interview . 5 void at confer (); . 6 // contract . 7 void signContart (); . 8 // booking . 9 void bookTacket (); 10 // singing . 11 void Sign (); 12 is // receive final payment 13 is void collentMoney (); 14 }
realstar
-
1 package org.west.demo; 2 3 public class RealStar implements Star{ 4 public void confer() { 5 6 } 7 8 public void signContart() { 9 10 } 11 12 public void bookTacket() { 13 14 } 15 16 public void sign() { 17 System.out.println("周杰伦:唱歌"); 18 } 19 20 public void collentMoney () { 21 22 } 23 }
starhandler
-
1 package org.west.demo; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 6 public class StarHandler implements InvocationHandler { 7 8 Star realStar; 9 10 public StarHandler(Star realStar) { 11 this.realStar = realStar; 12 } 13 14 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 15 16 System.out.println ( "pre-processing services" ); . 17 18 is Method.invoke (REALSTAR, args); . 19 20 is System.out.println ( "post-processing services" ); 21 is return null ; 22 is 23 is 24 25 } 26 is }
client
-
import java.lang.reflect.Proxy; public class Client { public static void main(String[] args) { Star realStar = new RealStar(); StarHandler handler = new StarHandler(realStar); Star proxy = (Star) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Star.class}, handler); proxy.sign(); } }
to sum up:
- When the method we tune into the proxy class will invoke method inside once. We can do some things in the process invoke methods.
-