1

我有以下课程

public class Booking{

    public String name;
    public String comment;

    public String session;

    public void test(){
        this.name = "hi";
    }
}

我使用以下方法对其进行检测:

cc.instrument(new ExprEditor(){
    public void edit(FieldAccess arg) throws CannotCompileException {
        if (arg.isWriter()) {
            StringBuffer code = new StringBuffer();
            code.append("$0.");
            code.append(arg.getFieldName());
            code.append("=$1.toUpperCase();");
            arg.replace(code.toString());
        }
    }           
});

现在当我这样称呼时:

Booking b = new Booking();
b.name = "hello";
System.out.println(b.name); // Edited correction

b.test();
System.out.println(b.name);

给我

hello // Externally, doesn't.
HI    // Internally, works as expected

我错过了什么?这似乎是我应该能够轻松完成的事情之一。

请不要告诉我我必须在所有课程上做一个毯子“fieldAccess.replace”?面向对象

4

1 回答 1

3

您的示例代码片段包含语句 b.name = "hello"; 没有被检测,因此它写入的值不会转换为大写。ExprEditor 只能转换由它检测的类的字段访问。如果您希望对“名称”字段的每次写入都转换为大写,则必须检测每个包含该字段的写入语句的类。

于 2012-02-13T03:19:58.617 回答