gpt4 book ai didi

java - AspectJ:访问私有(private)字段?

转载 作者:搜寻专家 更新时间:2023-11-01 01:55:32 25 4
gpt4 key购买 nike

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

我想我只需要让这方面有优势。我尝试了下面的代码,但是方面无法访问 id 字段。

public privileged aspect MyAspect {

public String Item.getId(){

return this.id;
}

一种可能性是像这篇博文中所示的用户反射(reflect):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());
}
}

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

关于java - AspectJ:访问私有(private)字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10721037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com