Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways of class agents

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what are the ways of class agency". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. let's follow the editor's way of thinking to study and learn "what are the ways of class agency"?

The way of five kinds of agency

We first define an interface and the corresponding implementation class to facilitate the subsequent use of the proxy class to add output information to the method.

"define Interface"

Public interface IUserApi {String queryUserInfo ();}

"implement Interface"

Public class UserApi implements IUserApi {public String queryUserInfo () {return "precipitate, share and grow so that you and others can gain something!" ;}}

good! Next we add an extra line of output to the class method using the proxy.

0. First add a little knowledge of reflection @ Test public void test_reflect () throws Exception {Class clazz = UserApi.class; Method queryUserInfo = clazz.getMethod ("queryUserInfo"); Object invoke = queryUserInfo.invoke (clazz.newInstance ()); System.out.println (invoke);}

Comments: there is almost a reflection where there are agents, they are a set of functional classes that cooperate with each other. In reflection, you can call methods, get properties, get annotations, and so on. All of these can be combined with the following class agents to complete the technical scenarios in various frameworks.

1. JDK agent public class JDKProxy {public static T getProxy (Class clazz) throws Exception {ClassLoader classLoader = Thread.currentThread (). GetContextClassLoader (); return (T) Proxy.newProxyInstance (classLoader, new Class [] {clazz}, new InvocationHandler () {public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System.out.println (method.getName ()) + "you are represented, By JDKProxy!") Return "precipitate, share and grow, so that both yourself and others can gain something!" ;}});} @ Test public void test_JDKProxy () throws Exception {IUserApi userApi = JDKProxy.getProxy (IUserApi.class); String invoke = userApi.queryUserInfo (); logger.info ("Test results: {}", invoke);} / * Test results: * * queryUserInfo you are represented, By JDKProxy! [main] INFO org.itstack.interview.test.ApiTest-Test results: precipitate, share and grow, so that you and others can gain something! * * Process finished with exit code 0 * /

Index: ⭐⭐

Scenario: middleware development, application of agent pattern and decorator pattern in design pattern

Comments: this kind of JDK comes with the class agent is a very commonly used, but also a very simple one. Basically can be seen in some middleware code, such as: database routing components, Redis components, etc., and we can also use this way to apply to the design pattern.

2. CGLIB agent public class CglibProxy implements MethodInterceptor {public Object newInstall (Object object) {return Enhancer.create (object.getClass (), this);} public Object intercept (Object o, Method method, Object [] objects, MethodProxy methodProxy) throws Throwable {System.out.println ("I was represented by CglibProxy"); return methodProxy.invokeSuper (o, objects);} @ Test public void test_CglibProxy () throws Exception {CglibProxy cglibProxy = new CglibProxy () UserApi userApi = (UserApi) cglibProxy.newInstall (new UserApi ()); String invoke = userApi.queryUserInfo (); logger.info ("Test results: {}", invoke);} / * Test results: * * queryUserInfo you are represented, By CglibProxy! [main] INFO org.itstack.interview.test.ApiTest-Test results: precipitate, share and grow, so that you and others can gain something! * * Process finished with exit code 0 * /

Scenarios: Spring, AOP aspects, authentication services, middleware development, RPC framework, etc.

Comments: CGLIB is different from JDK, its bottom layer uses the ASM bytecode framework to modify the script in the class to implement the proxy, so this proxy method does not need an interface to proxy like JDK. At the same time, thanks to the use of the bytecode framework, this proxy is 1.5 times faster than using the JDK proxy.

3. ASM agent public class ASMProxy extends ClassLoader {public static T getProxy (Class clazz) throws Exception {ClassReader classReader = new ClassReader (clazz.getName ()); ClassWriter classWriter = new ClassWriter (classReader, ClassWriter.COMPUTE_MAXS) ClassReader.accept (new ClassVisitor (ASM5, classWriter) {@ Override public MethodVisitor visitMethod (int access, final String name, String descriptor, String signature, String [] exceptions) {/ / method filter if (! "queryUserInfo" .equals (name)) return super.visitMethod (access, name, descriptor, signature, exceptions) Final MethodVisitor methodVisitor = super.visitMethod (access, name, descriptor, signature, exceptions); return new AdviceAdapter (ASM5, methodVisitor, access, name, descriptor) {@ Override protected void onMethodEnter () {/ / execute instructions Get static properties methodVisitor.visitFieldInsn (Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); / / load constant load constant methodVisitor.visitLdcInsn (name + "you are represented, By ASM!") ; / / call method methodVisitor.visitMethodInsn (Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;) V", false); super.onMethodEnter ();}} }, ClassReader.EXPAND_FRAMES); byte [] bytes = classWriter.toByteArray (); return (T) new ASMProxy (). DefineClass (clazz.getName (), bytes, 0, bytes.length). NewInstance ();} @ Test public void test_ASMProxy () throws Exception {IUserApi userApi = ASMProxy.getProxy (UserApi.class); String invoke = userApi.queryUserInfo () Logger.info ("Test results: {}", invoke);} / * Test results: * * queryUserInfo you are represented, By ASM! [main] INFO org.itstack.interview.test.ApiTest-Test results: precipitate, share and grow, so that you and others can gain something! * * Process finished with exit code 0 * /

Scenarios: full-link monitoring, cracking toolkits, CGLIB, Spring obtaining class metadata, etc.

Comments: this kind of agent is processed by bytecode programming, and its implementation is relatively complex, and it needs to know the relevant knowledge of Java virtual machine specification. Because every step of your proxy operation, you are operating bytecode instructions, such as Opcodes.GETSTATIC, Opcodes.INVOKEVIRTUAL, in addition to these, there are 200 commonly used instructions. But the way closest to the bottom is also the fastest way. Therefore, it is very common in some full-link monitoring using bytecode instrumentation.

4. Byte-Buddy proxy public class ByteBuddyProxy {public static T getProxy (Class clazz) throws Exception {DynamicType.Unloaded dynamicType = new ByteBuddy () .subclass (clazz) .method (ElementMatchers.named ("queryUserInfo")) .intercept (MethodDelegation.to (InvocationHandler.class)) .make () Return (T) dynamicType.load (Thread.currentThread (). GetContextClassLoader ()). GetLoaded (). NewInstance ();} @ RuntimeType public static Object intercept (@ Origin Method method, @ AllArguments Object [] args, @ SuperCall Callable callable) throws Exception {System.out.println (method.getName () + "you are represented, By Byte-Buddy!") ; return callable.call ();} @ Test public void test_ByteBuddyProxy () throws Exception {IUserApi userApi = ByteBuddyProxy.getProxy (UserApi.class); String invoke = userApi.queryUserInfo (); logger.info ("Test results: {}", invoke);} / * Test results: * * queryUserInfo you are represented, By Byte-Buddy! [main] INFO org.itstack.interview.test.ApiTest-Test results: precipitate, share and grow so that both yourself and others can gain something! * * Process finished with exit code 0 * /

Scenarios: AOP aspects, class agents, components, monitoring, logs

Comments: Byte Buddy is also a class library for bytecode operation, but the way to use Byte Buddy is simpler. Without understanding bytecode instructions, you can easily manipulate bytecode, control classes, and methods using a simple API. Compared with JDK dynamic agent and cglib,Byte Buddy, it has some advantages in performance. In addition, Byte Buddy was awarded the Duke's Choice Award by Oracle in October 2015. The award appreciates Byte Buddy's "tremendous innovation in Java technology".

5. Javassist proxy method public class JavassistProxy extends ClassLoader {public static T getProxy (Class clazz) throws Exception {ClassPool pool = ClassPool.getDefault (); / / get class CtClass ctClass = pool.get (clazz.getName ()); / / get method CtMethod ctMethod = ctClass.getDeclaredMethod ("queryUserInfo") / / strengthen ctMethod.insertBefore before the method ("{System.out.println (\"+ ctMethod.getName () +" you are represented, By Javassist\ ");}"); byte [] bytes = ctClass.toBytecode (); return (T) new JavassistProxy (). DefineClass (clazz.getName (), bytes, 0, bytes.length). NewInstance () } @ Test public void test_JavassistProxy () throws Exception {IUserApi userApi = JavassistProxy.getProxy (UserApi.class) String invoke = userApi.queryUserInfo (); logger.info ("Test results: {}", invoke) } / * Test results: * * queryUserInfo you have been represented, By Javassist * 20 main 23 main 39.139 [main] Test results-Test results: precipitation, sharing, growth, so that you and others can gain something! * * Process finished with exit code 0 * /

Scenario: full-link monitoring, class agent, AOP

Comments: Javassist is a very widely used bytecode plug-in framework, almost a large part of non-invasive full-link monitoring will choose to use this framework. Because it is not as risky to manipulate bytecode as ASM does, and it is also very functional. In addition, this framework can not only use the way it provides to write plug-in code directly, but also use bytecode instructions to control the generation of code, so it is also a very good bytecode framework.

Thank you for your reading, the above is the content of "what are the ways of class agency". After the study of this article, I believe you have a deeper understanding of the way of class agent. The specific use of the situation also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report