Before understanding jdk agency, we need to know what is a dynamic proxy? Dynamic proxy can do it?
Summary:
-
-
The real object implements the abstract objects of all functions
-
By Proxy class, create a proxy object, call the proxy method
-
In invoke InvocationHandler have chosen not to amend the existing modify real object method or method acting.
Abstract role
Package Penalty for com.it.proxy; / ** abstract roles: the definition of the function * / public interface Star { / ** sing @param Song * / void Sing (String Song); / ** performances @param Money * / void ACT ( int Money); }
Real role
Star is only responsible for singing, filming.
Package Penalty for com.it.proxy; / ** real character * / public class SuperStar the implements Star { @Override public void Sing (String Song) { System.out.println ( "star sang:" + Song); } @Override public void ACT ( int Money) { System.out.println ( "star appearance fees filming:" + Money); } }
jdk dynamic proxy role
Stars help agency fees, see the money does not meet the full requirements of the star.
Package com.it.proxy; Import java.lang.reflect.InvocationHandler; Import the java.lang.reflect.Method; Import the java.lang.reflect.Proxy; public class Fans { public static void main (String [] args) { / * use JDK dynamic proxy, creating a proxy object parameter 1: class loader parameter 2: All implemented interfaces parameter 3: interface method invocation, Star interface each method will be called a * / Star S2 = (Star) the Proxy.newProxyInstance ( s1.getClass (). getClassLoader (), new new class [] {Star. class }, new new of InvocationHandler () { / * for each method enhancements Parameter 1: proxy object can not be called directly, or recursion Parameter 2: The method of each object, such as: sing () act (), each method will be called a parameter 3: the parameter passing method, such as: song Return Value: returns the value of the method invocation }* / @Override public Object invoke (Object Proxy, method, method, Object [] args) throws the Throwable { // If the method is performed, it is determined whether or not less than 1000, not less than if performed, or call the original method String methodName = method.getName (); IF ( "ACT" .equals (methodName)) { // get the value of the parameter presentation int Money = ( int ) args [0 ]; IF (Money <1000 ) { System.out.println ( "low cost, not performed" ); return null ; } // other cases it calls the real object original method return Method.invoke (s1, args); // parameters of a real object, the method } });
// please fans of their favorite star singing appearances, filming s2.sing ( "because you're so beautiful" );
// low cost does not satisfy s2.act ( 500 ); } }