我知道可以使用反射做一些不错的事情,例如调用方法或更改字段的值。但是,是否可以在运行时以编程方式进行更大量的代码修改?
例如,如果我有一个方法:
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/