我想使用方面为私有id字段添加getter和setter.我知道如何通过方面添加方法,但是如何访问私有id字段?
我认为我只需要做出这方面的准备.我尝试了以下代码,但方面无法访问id字段.
public privileged aspect MyAspect {
public String Item.getId(){
return this.id;
}
Run Code Online (Sandbox Code Playgroud)
可能是用户反思,如本博客文章所示:http://blog.m1key.me/2011/05/aop-aspectj-field-access-to-inejct.html
反射是唯一的可能性,还是有办法用AspectJ做到这一点?
你确定你不能吗?我刚刚测试过它.这是我的完整代码:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因,这对您不起作用,您可以使用反射或此处所述的其他方式:http: //blogs.vmware.com/vfabric/2012/04/using-aspectj-for-accessing-private- members-without-reflection.html 但是,根据基准测试,它可能不值得.
| 归档时间: |
|
| 查看次数: |
4638 次 |
| 最近记录: |