The proxy tool class provided by JDK from 1.3 to provide some means of executing an interface in an agent way is applied in the implementation of Spring AOP;
jdk:1.8 code example
1. Interfaces that need to be represented
Package com.test.reflect;
/** *
@author hinsteny *
@Describtion *
@date 2016/12/2 *
@copyright: 2016 All rights reserved.
* * Public
interface Scholar {
String local = "Chiba";
String searching (string theme);
Default String infolocal () {return this
. local;
}
2. Implementation classes that need to be represented
Package com.test.reflect;
Import Org.slf4j.Logger;
Import org.slf4j.LoggerFactory;
Import Java.time.LocalDateTime;
/** *
@author hinsteny *
@Describtion *
@date 2016/12/2 *
@copyright: 2016 All rights reserved.
* * Public
class Scholarimpl implements scholar {
static final private Logger Logger = Loggerfactory.getlogger (Sc Holarimpl.class);
public static String Printtime () {
logger.info (????, Localdatetime.now (). toString ());
return ' time ';
@Override public
string searching (String theme) {
Logger.info (' scholar do search {} ', theme);
Return "Success";
}
3. Implementation of the Invocationhandler interface, where the agent execution, you can add custom business logic (such as logging, permission to intercept, statistics, etc.)
Package com.test.reflect.jdk;
Import Org.slf4j.Logger;
Import org.slf4j.LoggerFactory;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
/** *
@author hinsteny *
@Describtion *
@date 2016/12/2 *
@copyright: 2016 All rights reserved.
* * Public
class MyHandler implements Invocationhandler {
static final private Logger Logger = Loggerfactory.get Logger (myhandler.class);
Private object = null;
Public MyHandler (Object object) {
This.object = object;
}
@Override Public
Object Invoke (Object Proxy, Method method, object[] args) throws Throwable {
Logger.info ("Do s Omething before method {} ", Method.getname ());
Object ret = Method.invoke (this.object, args);
Logger.info ("Do something after method {}", Method.getname ());
return ret;
}
}
4. Test cases for viewing agent effects, and generation of class files for proxy classes
Package com.test.reflect.jdk;
Import Com.test.reflect.Scholar;
Import Com.test.reflect.ScholarImpl;
Import Org.junit.Test;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Sun.misc.ProxyGenerator;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.lang.reflect.Proxy;
/** * @author Hinsteny * @Describtion * @date 2016/12/2 * @copyright: 2016 All rights reserved.
* * public class Jdkproxytest {static final private Logger Logger = Loggerfactory.getlogger (Jdkproxytest.class);
@Test public void Testproxy () {//Scholarimpl object (being proxy) Managerimpl = new Scholarimpl ();
Business Agent class MyHandler Securityhandler = new MyHandler (MANAGERIMPL);
Obtain an instance of the proxy class ($Proxy 0 extends proxy implements Manager). Scholar Managerproxy = (scholar) proxy.newproxyinstance (JDKProxyTest.class.getClassLoader (), Managerimpl.getclass ()
. Getinterfaces (), Securityhandler); Logger.info ("Scholar Local is {}", MANAGERPROxy.
local);
Logger.info ("Scholar default method does and result is {}", managerproxy.infolocal ());
String theme = "Knowledge";
String result = managerproxy.searching (theme);
Logger.info ("result was {}", result); @Test public void Testgetproxyclass_1 () {//required to add Java command execution parameters [-dsun.misc.proxygenerator.savegeneratedfil Es=true]//Then the generated dynamic proxy object will be named from [$Proxy #.class] (#从0开始依次加1递增) System.out.println in the subdirectory of the following directory (Com\sun\proxy) (
System.getproperty ("User.dir"));
Testproxy ();
can go to the corresponding directory to see the generated dynamic class class files, decompile the dynamic class of Java code Logger.info ("Finish at here {}"); @Test public void Testgetproxyclass_2 () {//Get the byte code of the proxy class byte[] Classfile = Proxygenerator.generat
Eproxyclass ("$Proxy One", ScholarImpl.class.getInterfaces ());
Write file String path = "d://data/$Proxy 1.class";
FileOutputStream out = null;
try {out = new FileOutputStream (path); Out.wRite (Classfile);
Out.flush ();
catch (Exception e) {e.printstacktrace ();
Finally {try {if (out!= null) out.close ();
catch (IOException e) {e.printstacktrace (); }
}
}
}
5. decompile view generate dynamic class source code
Package com.sun.proxy;
Import com.test.reflect.*;
Import java.lang.reflect.*;
Public final class $Proxy extends Proxy implements scholar {private static method M1;
private static method m2;
private static method M4;
private static method M3;
private static method M0;
Public $Proxy (Final Invocationhandler Invocationhandler) {super (Invocationhandler); Public Final Boolean equals (Final Object o) {try {return (Boolean) Super.h.invoke (this, $Proxy
20.M1, new object[] {o}); catch (Error |
RuntimeException error) {throw;
The catch (Throwable t) {throw new undeclaredthrowableexception (t); } Public final String toString () {try {return (String) Super.h.invoke (this, $Proxy 20.m2, n
ULL); catch (Error |
RuntimeException error) {throw; catch (Throwable t) {throw new UndEclaredthrowableexception (t); } Public final String infolocal () {try {return (String) Super.h.invoke (this, $Proxy 20.m4,
NULL); catch (Error |
RuntimeException error) {throw;
The catch (Throwable t) {throw new undeclaredthrowableexception (t); } public final string searching (final string s) {try {return (string) Super.h.invoke.
$Proxy 20.m3, new object[] {s}); catch (Error |
RuntimeException error) {throw;
The catch (Throwable t) {throw new undeclaredthrowableexception (t);
} public final int hashcode () {try {return (int) Super.h.invoke (this, $Proxy 20.m0, NULL); catch (Error |
RuntimeException error) {throw;
The catch (Throwable t) {throw new undeclaredthrowableexception (t);
}
} static {try {$Proxy 20.m1 = Class.forName ("Java.lang.Object"). GetMethod ("Equals", Class.forName ("Ja
Va.lang.Object "));
$Proxy 20.m2 = Class.forName ("Java.lang.Object"). GetMethod ("ToString", (class<?>[)) new class[0]);
$Proxy 20.m4 = Class.forName ("Com.test.reflect.Scholar"). GetMethod ("Infolocal", (class<?>[)) new class[0]); $Proxy 20.m3 = Class.forName ("Com.test.reflect.Scholar"). GetMethod ("Searching", Class.forName ("java.lang.String"))
;
$Proxy 20.m0 = Class.forName ("Java.lang.Object"). GetMethod ("Hashcode", (class<?>[)) new class[0]);
The catch (Nosuchmethodexception ex) {throw new Nosuchmethoderror (Ex.getmessage ());
catch (ClassNotFoundException ex2) {throw new Noclassdeffounderror (Ex2.getmessage ());
}
}
}
Note: