Java字节码操作和Java反射API?

Cur*_*ind 0 java reflection bytecode-manipulation javassist

我最近遇到了"字节码操作"这个术语(为了研究这个问题,我在看到使用Hibernate的应用程序中的日志的同时看到了字节码提供程序).我也知道(有点)Java Reflection API.

这两个概念是否相似?他们之间有什么区别?什么时候用哪个?

bed*_*rin 9

Reflection API允许您访问有关已加载到JVM的类的成员(字段,方法,接口等)的信息.此API不允许修改类的行为,除了一些基本的东西,如调用私有方法.

Reflection API适用的一些示例

  • 依赖注入框架可以将依赖项设置为所有者对象的私有字段.
  • 您可以使用反射为类生成equals/hashCode/toString方法,而无需枚举所有字段并在添加新字段或删除现有字段时修改这些方法
  • 使用Relfection Api将类序列化为JSON/XML/Yaml或任何其他格式,而无需枚举所有字段

相反,ByteCode操作允许您对磁盘上的某些.class文件或使用Java Agent API加载到JVM的类进行任何更改.

一些字节码操作适用的例子:

  • Java标准库中的代理仅支持代理接口; 字节码操作允许您在类方法周围添加建议
  • 单元测试的模拟框架允许替换私有静态方法的返回值 - 它是使用字节码操作实现的
  • Profilers用时间记录代码包装每个方法

这是它的外观

private void foo() {
    long start = System.currentTimeMillis(); // inserted by bytecode manipulation
    Profiler.enterMethod("foo"); // inserted by bytecode manipulation
    try { // inserted by bytecode manipulation
        //  original method code
    } finally { // inserted by bytecode manipulation
        Profiler.exitMethod("foo", System.currentTimeMillis() - start); // inserted by bytecode manipulation
    } // inserted by bytecode manipulation
}
Run Code Online (Sandbox Code Playgroud)