In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what are the advantages of Agent without Jar package". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
When it comes to JavaAgent, many people say a few words, just like the Peacock Ling in Gulong's martial arts novel, which is very powerful and has legends all over the world. But not many people have really seen it.
Although JavaAgent is not so mysterious, it always gives people the feeling of being high and low, and it is rarely seen in business except for some middleware products and large frameworks.
There are many reasons: it may not be necessary, it is necessary to develop a separate Agent Jar file, and transform development of classes within Jar is not easy.
We know that both the startup Java Agent and the runtime dynamic attach to the remote JVM are to get the Instrument and modify the bytecode of the class. Such a low-level thing, of course, it is not easy to use.
But just as machine language is inconvenient, people invented assembly language and discovered high-level language. The operation of bytecode is similar, people feel that it is difficult to manipulate bytecode directly, and they need to deeply understand the JVM specification, which is not what most people like, so the ASM framework appears; but there is still a shadow of the specification, not too "advanced", so there are "advanced" tools such as Javassist.
The tool we're going to talk about today, similar to Javassist, provides a higher-level API to operate class, which is more friendly to ordinary programmers.
Just like today, when people shop and read books, they all believe in professional platforms or experts' recommendations, such as XX strict selection and XX Reading Club recommendation. The tool we are talking about today is recommended by Duke, yes, it is the mascot of Java, this little fat man. Today's tool was named "Duke's Choice award" by Oracle in 2015.
In addition to Duke, the framework has also been recognized by many developers, with more than 70 million downloads each year.
The tool is: Bytebuddy.
You can see from the name that it is determined to be a good partner of bytecode. So it can also be seen in many open source frameworks.
Now that there are a lot of tools in place, what difference can byteBuddy make?
In addition to the simplicity and ease of operation on API, officials themselves emphasize dynamic "code generation and bytecode manipulation" at run time, eliminating the need for a Java compiler.
Let's take a look at how the official website introduces itself, followed by a few code snippets, and Get will arrive soon.
Official website: https://bytebuddy.net/
Byte Buddy is a code generation and manipulation library for creating and modifying Java classes during the runtime of a Java application and without the help of a compiler. Other than the code generation utilities that ship with the Java Class Library, Byte Buddy allows the creation of arbitrary classes and is not limited to implementing interfaces for the creation of runtime proxies. Furthermore, Byte Buddy offers a convenient API for changing classes either manually, using a Java agent or during a build.
Reading comprehension begins. You must have seen the point:
"code generation"
"creating and modifying Java classes"
The author thoughtfully added a small print to describe the advantages of the framework. The main point is:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
No need to understand bytecode, nor need to understand class file format
API is non-intrusive and easy to understand.
Highly customizable and can be customized at will
I think I should add this point, too, that you can Attach to JVM without writing Java Agent, think of ByteBuddy as an Agent, and install directly at run time. Cool .
You can intercept and modify classes without writing JVM Agent. Let's get to know the guy who uncovers the bytecode and modifies the dark magic.
In order to do some operations on Class, we usually can't do without JVM Agent. Whether you connect directly at startup or dynamically Attach to the corresponding JVM at run time, Agent is required. That is, we are familiar with the trigger portals of premain and agentmain, through which we can get Instrumentation, which can be used for transform and redeine.
But the use of this thing, always give people the feeling of "spring snow", let people feel like dark magic, generally will not easily try to use.
With ByteBuddy, you no longer have to envy some of the framework's "runtime enhancements", "dynamic weaving", and so on.
How to get started?
Just download the Jar file or Maven to add dependencies and you can run.
For example, the official HelloWorld
Class dynamicType = new ByteBuddy () .subclass (Object.class) .method (ElementMatchers.named ("toString")) .intercept (FixedValue.value ("Hello World!")) .make () .load (getClass (). GetClassLoader ()) .getLoop (); assertThat (dynamicType.newInstance (). ToString (), is ("Hello World!"))
Directly rewrite the toString method of Object.
Or, for example, we can use this when developing Java Agent, man.
Public static void premain (String args, Instrumentation inst) {AgentBuilder agentBuilder = new AgentBuilder.Default () AgentBuilder.Transformer transformer = new AgentBuilder.Transformer () {public DynamicType.Builder transform (DynamicType.Builder builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {String className = typeDescription.getCanonicalName () Builder = builder.method (ElementMatchers.any ()) / / matches any method. Intercept (MethodDelegation.to (new SimplePackageInstanceMethodInterceptor ()); return builder;}}; agentBuilder = agentBuilder.type (ElementMatchers.nameStartsWith ("com.example.hello.sample")) .transform (transformer); agentBuilder.installOn (inst);}
When intercept matching in a class, you can qualify it by the class name, and match the method name with different patterns. The ElementMatchers here can be used in matching scenarios such as class name and method name.
/ / ElementMatchers.named ("abc") / / method with a specific name / / ElementMatchers.nameStartsWith ("hello") / / what begins / / ElementMatchers.nameEndsWith ("test") / / what ends with
We see agentBuilder.installOn (inst) in the previous code
Class modification is made through the Instrument of JavaAgent.
AgentBuilder also provides a magical method:
AgentBuilder.installOnByteBuddyAgent ()
This enables runtime enhancements without providing a Jar file. It is important to note, however, that when using this, be sure to execute this line of code first, which is the secret of its implementation:
ByteBuddyAgent.install ()
Because ByteBuddy itself is also Attach as a Jar, and then add other subsequent enhancements, whether it is like a "Trojan horse":)
In addition, ByteBuddy also supports an Advice implementation similar to AOP, which can implement the control of OnMethodEnter and OnMethodExit after intercepting the specified method, in which you can complete the logic of bypassing user code and executing custom content.
At the beginning, we also mentioned code generation. This is also a piece of cake for ByteBuddy.
As in the above code, you need to get the AgentBuilder first, and then directly specify the method name, the corresponding parameters, access control characters, etc., when executing the tranform.
DynamicType.Builder.MethodDefinition.ExceptionDefinition hello = builder.defineMethod (methodName, types, Visibility.PUBLIC) .withparameters (m.getParameters () .asTypeList ())
Another example is to annotate a method at run time.
Builder.method (ElementMatchers.named ("methodName")) .intercept (SuperMethodCall.INSTANCE) .annotateMethod (AnnotationDescription.Builder.ofType (TestAnnotation.class) .define ("testValue", 123) .build ())
Is it very powerful?
This is the end of the content of "what are the advantages of Agent without Jar package". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.