作者:zackcoolgirl_497 | 来源:互联网 | 2022-12-25 15:34
What I am trying to do: I want to have a pre-compiled java byte-code file, and be able to place a "mark" in some places. Later I want to analyze this file using ASM and replace mark with some code. So, how can I implement this? Currently I am trying to do it, by inserting invocations of empty static method, but I still feeling like I am doing something wrong. Is there a better way to do this?
我想做的是:我希望有一个预编译的java字节码文件,并且能够在某些地方放置“标记”。后来我想用ASM分析这个文件,用一些代码替换mark。那么,我该如何实现呢?目前我正在尝试通过插入空静态方法的调用来实现它,但我仍然觉得我做错了什么。有一个更好的方法吗?
P.S. If more general, I want to have some precompiled class template, for example:
附:如果更一般,我想要一些预编译的类模板,例如:
public class Main {
public static void Main(String... args){
System.out.println("Program starts!");
//I want to insert code here
System.out.println("Bye!");
}}
1 个解决方案
There is no Java statement without a predefined meaning, well, maybe with the exception of the empty statement ;
which doesn’t create code that you can find in the byte code. There are annotations, but these can only be used to mark another code fragment, not to create a stand-alone statement within your code.
没有预定义的Java语句,好吧,可能除了空语句之外;它不会创建您可以在字节代码中找到的代码。有注释,但这些只能用于标记另一个代码片段,而不是在代码中创建独立语句。
So you have to choose a statement to assign it the meaning of being a mark in your template code and your solution of using an invocation of a dedicated empty method is a perfect candidate for such a mark. Since it’s new meaning does not rely on the kind of statement but on the target method which resides in a class whose name is distinguishable from all other classes, there is no conflict between your mark and other statements.
因此,您必须选择一个语句来为其指定在模板代码中作为标记的含义,并且使用专用空方法调用的解决方案是此类标记的完美候选。由于它的新含义不依赖于语句类型,而是依赖于目标方法,该方法位于名称可与其他类区分开的类中,因此标记与其他语句之间不存在冲突。
But you should consider that the framing class code is rather trivial compared to the code you will generate when implementing a compiler for any non trivial language. In most cases, the logic of patching the generated code into an existing code will exceed the complexity of just generating a complete class file.
但是你应该考虑到,与为任何非平凡的语言实现编译器时生成的代码相比,框架类代码相当简单。在大多数情况下,将生成的代码修补到现有代码中的逻辑将超过仅生成完整类文件的复杂性。
If you really have large pieces of unchanging code you should consider placing them into their own classes and generate classes using or extending them. This simplifies the code generation and avoids code duplication (the same reason why these techniques are used in manually written code).
如果您确实拥有大量不变的代码,则应考虑将它们放入自己的类中,并使用或扩展它们来生成类。这简化了代码生成并避免了代码重复(这些技术用于手动编写代码的原因相同)。