java - Java 中的程序代码修改(例如变量提取)

标签 java reflection bytecode-manipulation

我知道可以使用反射做一些不错的事情,例如调用方法或更改字段的值。但是,是否可以在运行时以编程方式进行更大量的代码修改?

例如,如果我有一个方法:

public void foo(){
    this.bar = 100;
}

我可以编写一个程序来修改此方法的内部结构,注意到它为字段分配了一个常量,并将其转换为以下内容:

public int baz = 100;

public void foo(){
    this.bar = baz;
}

也许 Java 并不是真正适合做这种事情的语言 - 如果不是,我愿意接受有关语言的建议,这些语言将允许我基本上以这种方式重新解析或检查代码,并能够更改它如此精确。不过,我可能在这里做白日梦,所以请告诉我是否也是这种情况。

最佳答案

只是添加 friend 的建议 - Apache Commons 的 BCEL 看起来很棒:

http://commons.apache.org/bcel/manual.html

The Byte Code Engineering Library (Apache Commons BCEL™) is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class). Classes are represented by objects which contain all the symbolic information of the given class: methods, fields and byte code instructions, in particular. Such objects can be read from an existing file, be transformed by a program (e.g. a class loader at run-time) and written to a file again. An even more interesting application is the creation of classes from scratch at run-time. The Byte Code Engineering Library (BCEL) may be also useful if you want to learn about the Java Virtual Machine (JVM) and the format of Java .class files.

关于java - Java 中的程序代码修改(例如变量提取),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13647193/

相关文章:

java - 如何即时从类定义中删除方法?

java - ASM 内联字节码方法期间重新映射变量

java - MethodVisitor 抛出 ClassFormatError

java - 如何截取图像 (.png) 的一部分并将其作为纹理存储在 libGDX 中

java - 为什么编译器将泛型类型转换为原始类型?

java - 无法掌握 Guice 方法拦截器的窍门(bindInterceptor 期间出现空指针异常)

java - 减少字符串

C# - 将 .NET 程序集加载到单独的 AppDomain 中以便卸载它

c# - 转换通过反射创建的类时遇到问题

c# - 如何解决 C# 中的错误 "ByRef return value not supported in reflection invocation"?