字节码操作拦截设置字段的值 [英] Bytecode manipulation to intercept setting the value of a field

查看:149
本文介绍了字节码操作拦截设置字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用像 ASM cglib 这样的库,有没有办法将字节码指令添加到要执行的类中每当设置一个类字段的值时代码?

Using a library like ASM or cglib, is there a way to add bytecode instructions to a class to execute code whenever the value of a class field is set?

例如,假设我有这个类:

For example, let’s say I have this class:


   public class Person
   {  
       bool dirty;
       public String name;
       public Date birthDate;
       public double salary;
   }

假设一段代码包含以下行:

Let’s say a section of code contains this line:


person.name =Joe;

我希望拦截此指令,以便标志设置为 true 。我知道这对于setter方法是可行的 - person.setName(Joe) - 因为类方法可以通过字节码操作来修改,但我想做同样的事情字段的内容

I want this instruction to be intercepted so the dirty flag is set to true. I know this is possible for setter methods -- person.setName ("Joe") -- as class methods can be modified by bytecode manipulation, but I want to do the same thing for a field.

这是否可行,若然,如何

编辑

我想避免修改访问该类的代码部分,我正在寻找一种将拦截代码保留为 Person 类的一部分的方法。是否存在用于字段访问的伪方法,类似于Python类中的属性?

I want to avoid modifying the code section that accesses the class, I'm looking for a way to keep the interception code as part of the Person class. Are there a pseudo-methods for field access, similar to properties in Python classes?

推荐答案

有两个用于更新字段的字节码: putfield putstatic (参见 http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc11.html )。这些将在using类的代码中找到,因此无法简单地修改 Person

There are two bytecodes for updating fields: putfield and putstatic (see http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc11.html). These will be found in the code for the using class, so there's no way to simply modify Person.

这篇关于字节码操作拦截设置字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆