5

我想使用方面为私有 id 字段添加 getter 和 setter。我知道如何通过方面添加方法,但是如何访问私有 id 字段?

我认为我只需要使方面得到授权。我尝试了以下代码,但方面无法访问 id 字段。

public privileged aspect MyAspect {

public String Item.getId(){

    return this.id;
}

一种可能性是用户反映,如本博客文章所示:http: //blog.m1key.me/2011/05/aop-aspectj-field-access-to-inejct.html

反射是唯一的可能性还是有办法用 AspectJ 做到这一点?

4

1 回答 1

8

你确定你不能?我刚刚测试并运行了。这是我的完整代码:

package com.example;

public class ClassWithPrivate {
    private String s = "myStr";
}

==========

package com.example.aspect;

import com.example.ClassWithPrivate;

privileged public aspect AccessPrivate {

    public String ClassWithPrivate.getS() {
        return this.s;
    }

    public void ClassWithPrivate.setS(String str) {
        this.s = str;
    }
}

==========

package com.example;

public class TestPrivate {

    public static void main(String[] args) {

        ClassWithPrivate test = new ClassWithPrivate();
        System.out.println(test.getS());
        test.setS("hello");
        System.out.println(test.getS());
    }
}

如果由于某种原因,这对您不起作用,您可以使用反射或此处描述的其他方式: https ://web.archive.org/web/20161215045930/http://blogs.vmware.com/vfabric/ 2012/04/using-aspectj-for-accessing-private-members-without-reflection.html 但是,根据基准,它可能不值得。

于 2012-05-24T14:27:30.323 回答