Use JRebel Start the project with VM One of the parameters is "-javaagent:D:\jrebel_5.6.0\jrebel.jar".

javaagent What is it? ? java -help After that, I see the following information :

Java Agents are not part of the application ,instrument Support Java Monitor or redefine running services as agents .
We can pass through without modifying the program code Instrumentation API Change the running java Program .
And what we use "-javaagent:jarpath[=options] " Parameters are one way , That is, execute the agent before the application starts .

The parameter value is one jar route , Let's try to write a proxy first , And then export it as jar.
Since there is no real purpose , Then take java agent Focus on the use of , Try to be as simple as possible .
So-called agent The code implementation of is one with premain() Class of method , But this method is not based on an abstraction , It's defined into classes .
premain The declaration of a method can be public static void premain(String args, Instrumentation inst) or public static void premain(String args).
Parameters String args Corresponding "-javaagent:jarpath[=options] " Medium options.
Parameters Instrumentation inst Is passed in by the runtime Instrumentation example .

package pac.testcase.basic.agent;
import java.lang.instrument.Instrumentation;
public class TestAgent {
public static void premain(String agentArgs, Instrumentation inst){
System.out.println("Alvez Agent:::");
}
}

take TestAgent Export to jar, Suppose my export path is "D:/myAgent.jar".
Write a random main Method , Add parameters "-javaagent:D:/myAgent.jar" And run :

package pac.testcase.basic.agent;
public class TestAgentMain {
public static void main(String[] args) throws InterruptedException {
System.out.println("code in runtime::");
}
}

The results suggest :
Error occurred during initialization of VM
agent library failed to init: instrument
Failed to find Premain-Class manifest attribute in D:/myAgent.jar

Need to be in MANIFEST.MF Add an attribute to , Specify manually premain class, For example, in this case, it is changed as follows :
Manifest-Version: 1.0
Premain-Class: pac.testcase.basic.agent.TestAgent
Can-Redefine-Classes: true

Then you can run , Results output :
Alvez Agent:::
code in runtime::

But it's just that it's not interesting , We can only specify... Before the application runs premain class, As a result, it's still not possible to make changes at run time , Is there any way to specify an agent after it runs ?
Something unexpected happened when the program was running , At this time, it is more meaningful to use the agent to solve the emergency situation temporarily , But the solution to this problem is not premain It is agentmain.
and premain The similarity is , The method declaration is almost the same , namely public static void agentmain(String args, Instrumentation inst) or public static void agentmain(String args).

package pac.testcase.basic.agent;
import java.lang.instrument.Instrumentation;
public class TestAgent {
public static void agentmain(String agentArgs, Instrumentation inst){
System.out.println("Alvez Agent:::");
}
}

in addition , stay MANIFEST The specified property name is also changed to Agent-Class, as follows :
Manifest-Version: 1.0
Agent-Class: pac.testcase.basic.agent.TestAgent
Can-Redefine-Classes: true
(Ps: Even if Premain-Class and Agent-Class No problem .)

and Premain The difference is , Use Agentmain We need to use tools.jar Medium com.sun.tools.attach.VirtualMachine, Delegate jar Bind to the specified VM, such as :

VirtualMachine vm = VirtualMachine.attach("");
vm.loadAgent("");

Get the corresponding VM, And pass loadAgent Appoint agentmain jar.

Both use Instrumentation

Just look at the statement of this method , I didn't think too much about it , Got a premain Method initialization Instrumentation:

public class ObjectSizeUtils {
private static Instrumentation inst = null;
public static void premain(String agentArgs, Instrumentation inst) {
ObjectSizeUtils.inst = inst;
} public static long sizeOf(Object o){
if(inst == null) throw new IllegalStateException("not initialized yet");
return inst.getObjectSize(o);
}
}

export jar And in MANIFEST.MF Medium plus :

Premain-class: pac.testcase.utils.ObjectSizeUtils
Can-Redefine-Classes: false

Just write an entity class , For testing :

class Person{
private String name;
private String life; public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getLife() {return life;}
public void setLife(String life) {this.life = life;}
}

Okay , Add... To the operating parameters -javaagent, Execute to see what will be output :

 @Test
public void testSizeUtils(){
Person person = new Person("Alvez","make me death before you make me old");
logger.info(String.valueOf(sizeOf(person)));
logger.info(String.valueOf(sizeOf(person.getName())));
logger.info(String.valueOf(sizeOf(person.getLife())));
} static final Logger logger = LoggerFactory.getLogger(ObjectSizeUtils.class);

It turns out to be strange ...

Why? person The properties of the than person Also big ? wait ,name and life There seems to be something wrong with the size of ....
I went back to my textbook and found that things were not what I expected , I need to add up all the elements in the object to achieve the effect I want ....
It seems that there are still some things that need to be solved in person , therefore :

public class ObjectSizeUtils {
private static Instrumentation inst = null;
public static void premain(String agentArgs, Instrumentation inst) {
ObjectSizeUtils.inst = inst;
} public static long sizeOf(Object o) throws IllegalAccessException {
if(inst == null) throw new IllegalStateException("not initialized yet");
SizeCounter sizeCounter = new SizeCounter();
sizeOf(o, sizeCounter);
return sizeCounter.getSize();
} public static void sizeOf(Object o,SizeCounter sizeCounter) throws IllegalAccessException {
if(o!=null){
sizeCounter.addSize(inst.getObjectSize(o));
Class c = o.getClass();
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
int mod = f.getModifiers();
if(Modifier.isStatic(mod) || f.getType().isPrimitive()){
continue;
}
f.setAccessible(true);
Object o1 = f.get(o);
sizeOf(o1,sizeCounter);
}
}
} } class SizeCounter{
private long size; public long getSize() {
return size;
} public void setSize(long size) {
this.size = size;
} public void addSize(long size){
this.setSize(this.getSize() + size);
}
}

This code is not complete , There are many other factors that have not been taken into account , This is the general idea .

Here are agent jar Of documents Manifest Attributes:
Premain-Class 
If JVM Agent specified at startup , Then this property specifies the proxy class , Which contains premain Class of method . If JVM Agent specified at startup , Then this property is required . If the attribute does not exist , that JVM Will be suspended . notes : This property is the class name , Not a filename or path .

Agent-Class 
If support is implemented VM Mechanism of starting agent at a certain time after startup , Then this property specifies the proxy class . Which contains agentmain Class of method . This property is required , If it doesn't exist , Agent will not start . notes : This is the name of the class , Instead of a filename or path .

Boot-Class-Path 
List of paths searched by the bootstrap classloader . A path represents a directory or library ( On many platforms, it's usually used as JAR or zip Library referenced ). After a failure to find the platform specific mechanism for a class , The bootstrap class loader searches these paths . Search for paths in the order listed . Paths in the list are separated by one or more spaces . Path usage hierarchy URI Path component syntax for . If the path is in a slash character (“/”) start , Absolute path , Otherwise, it is a relative path . Relative path based on Proxy JAR Absolute path analysis of files . Ignoring malformed and non-existent paths . If the agent is in VM It started at a certain moment after it started , Then ignoring does not mean JAR Path to file . This property is optional .

Can-Redefine-Classes 
Boolean value (true or false, Case independent ). Whether the classes required by this proxy can be redefined .true Values other than are considered to be false. This property is optional , The default value is false.

Can-Retransform-Classes 
Boolean value (true or false, Case independent ). Whether the classes required by this proxy can be retransformed .true Values other than are considered to be false. This property is optional , The default value is false.

Can-Set-Native-Method-Prefix 
Boolean value (true or false, Case independent ). Whether the native method prefix required by this agent can be set .true Values other than are considered to be false. This property is optional , The default value is false

Java - Instrumentation More articles about

  1. java instrumentation &JVMTI

    Java Instrumentation ( Reference resources :http://www.ibm.com/developerworks/cn/java/j-lo-jse61/) brief introduction : Use Instrumentatio ...

  2. Cao Gong said Spring Boot Source code (25)-- Spring Annotation scanning Swiss Army knife ,ASM + Java Instrumentation, By the way Jar Packet cracking

    Let me write it out front Relevant background and resources : Cao Gong said Spring Boot Source code (1)-- Bean Definition What is it , attach spring Mind map sharing Cao Gong said Spring Boot Source code (2)-- Bean ...

  3. Java Instrumentation Study of pile insertion technology

    Instrumentation Basics openrasp Used in the Instrumentation technology , Its greatest function , It is the dynamic change and operation of class . Use Instrumentation You can actually develop an agent to ...

  4. java senior - Dynamic injection replacement class Instrumentation

    Introduce utilize java.lang.instrument( Container class ) Do something dynamic Instrumentation( Perform the container ) yes Java SE 5 New features . Use Instrumentation, Developers can construct ...

  5. Java Fiber Library in – Quasar

    source : Bird's nest , colobu.com/2016/07/14/Java-Fiber-Quasar/ If there are good articles to contribute , Please click on → Here's the details A recent problem is probably a common problem in microservice architecture : clothing ...

  6. java Basics -01 Basic concepts

    java Characteristics Cross platform The so-called platform , We can understand it as an operating system . Most languages are not cross platform , such as c The program of language is windows and linux You need to write different code on the . java The program is running in JVM(Java Vir ...

  7. Geek time - The left ear to listen to the wind - Programmer strategy -Java The underlying knowledge

    Java Bytecode related Bytecode programming , That is, dynamic modification or dynamic generation Java Bytecode .Java Bytecode is equivalent to assembly , Some of the details . Java Zone: Introduction to Java Byte ...

  8. Do not modify the source code , Dynamic Injection Java Code method ( turn )

    from :https://blog.csdn.net/hiphoon_sun/article/details/38707927 Sometimes , We need to go to a third party without modifying the source code JAVA The program injects its own generation ...

  9. java agent Technical principle and simple implementation

    notes : This article defines - The operation of adding corresponding logic before and after function execution is collectively called MOCK 1. Introduction One day with QA When students communicate , Find out QA When a method is called by a classmate , There is a need to stop this method for a while , I am very curious about the function implementation of this part , therefore ...

Random recommendation

  1. Hadoop Translation of official documents —— YARN ResourceManager High Availability 2.7.3

    ResourceManager High Availability (RM High availability ) Introduction( brief introduction ) Architecture( framework ) RM Failover(RM Fail over ) Rec ...

  2. StringIO Study

    StringIO StringIO The behavior and file Objects are very much like , But it's not a file on disk , It's a memory “ file ”, We can operate as disk files StringIO. A simple example , Make you right StringIO There is a ...

  3. MVC in CheckBox

    One . Single Checkbox 1.View file <%= Html.CheckBoxFor(model => model.IsNeverExpired)%> 2. Generated HTML by < ...

  4. C Language &gt; The pointer to the pointer

    Int **pt; A pointer to a pointer : { int ** pt; // A pointer to a pointer ; int *ppt; ; ppt = &a; pt = &ppt; printf(" ...

  5. full join no The use of full connection

    Query the salary range of each department , according to 1000~2000,2000~3000.... This format shows the number of people select * from (select job,count(*) as "1000~2000& ...

  6. Blinn-Phong Model

    I'm looking at the basic lighting model recently , More interesting is the specular model , There are two kinds : 1.Phong Model R = 2*N(dot(N, L)) - L specular = lightColor * SpecularCol ...

  7. Arduino Show PM2.5

    This code is usually copied , Just a little change The code is as follows : #include <Wire.h> #include <LiquidCrystal_I2C.h> #include < ...

  8. Experiment — Security miscellaneous ——WP And The goddess

    Click on the link to download the compressed file and get open TXT file : It can be seen that it is base64, So long , That is to turn it into a picture ~ Address :http://www.vgot.net/test/image2base64.php? Then is ...

  9. http Socket A long connection

    file :http://www.cocoachina.com/ios/20160602/16572.html socket( Socket ) Is the cornerstone of communication , It's supporting TCP/IP Basic operation unit of network communication of protocol , Including the Internet ...

  10. 10.N Find out whether the sum of the integers is K[ Deep search ]

    /* From books , This algorithm is very complicated !*/ #include <iostream> using namespace std; ,,,}; ; bool dfs(int i,int sum) { if ...