什么是 Java 字节码注入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3470949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:58:51  来源:igfitidea点击:

What is Java bytecode injection?

javabytecode

提问by Marcus Leon

What exactly is Java bytecode injection and why would one use it?

Java 字节码注入到底是什么,为什么要使用它?

回答by Amir Afghani

Java code compiles into bytecode (Foo.java ->> Foo.class). Bytecode injection is modifying Foo.classat runtime to inject code into it right before its loaded and run.

Java 代码编译为字节码 ( Foo.java ->> Foo.class)。字节码注入是Foo.class在运行时修改以在加载和运行之前将代码注入其中。

Imagine a scenario where I want to find out how many times method

想象一个场景,我想找出多少次方法

public void bar();

is invoked in Foo.class. I could write an agent using java.lang.instrumentthat intercepts Foo.classduring class load, modifies it using ASMso that bar()calls com.amir.agent.incrementCount()on method entry.

在 中调用Foo.class。我可以编写一个使用在类加载期间java.lang.instrument拦截的代理Foo.class,使用ASM修改它以便bar()调用com.amir.agent.incrementCount()方法入口。

Now I can run my program:

现在我可以运行我的程序:

$java -javagent:MyAgent Foo  //assuming Foo has a main() defined

and at runtime, Foo.classwill not only do its normal work, it will also do work I defined in MyAgenteach time bar()is invoked.

并且在运行时,Foo.class不仅会做它的正常工作,还会做我在MyAgent每次bar()调用时定义的工作。

For a pointer on writing an agent from scratch, start here.

有关从头开始编写代理的指南,请从此处开始。

回答by Ivan

First google search gives an interesting read Java Programming: Bytecode Injection

第一次谷歌搜索给出了一个有趣的阅读Java Programming: Bytecode Injection

回答by stacker

To address the second part of your question. I use it since I'm lazy and don't want the to spend half of my (working) life writing getters and setters. Instead I put an annotation @Data before my class definition and everything is done.

解决您问题的第二部分。我使用它是因为我很懒惰并且不想花费我(工作)生活的一半时间来编写 getter 和 setter。相反,我在类定义之前添加了一个注释 @Data,一切都完成了。

See the 3 minutes video demonstration on Project Lombok.

请参阅有关Project Lombok的 3 分钟视频演示。