java注释修改_java – 使用注释修改方法

注释处理是错误的方法,从

Wikipedia:

When Java source code is compiled,

annotations can be processed by

compiler plug-ins called annotation

processors. Processors can produce

informational messages or create

additional Java source files or

resources, which in turn may be

compiled and processed, but annotation

processors cannot modify the annotated

code itself.

人们建议你正确的方法 – AOP.具体可以使用AspectJ. “快速结果”的方式是(如果使用Eclipse):

1)安装AJDT(AspectJ开发工具)

2)创建AspectJ项目并添加您的类和注释

3)创建方面:

public aspect Processor {

private StaticReference z;

pointcut generic()

// intercept execution of method named test, annotated with @Anno1

// from any class type, annotated with @Anno2

: execution(@Anno2 * (@Anno1 *).test())

// method takes no arguments

&& args ();

// here you have write what you want method actually does

void around () : generic() {

z.invokeToAll();

}

}

现在你可以执行测试,你会看到它的工作原理;)AJDT自动编译代码,所以不需要任何手工工作,希望这就是你所说的“魔术”;)

更新:

如果你在test()方法中的代码取决于Anno1注释值,那么在内部方面你可以通过这种方式获得它执行的类注释:

void around () : generic() {

Annotation[] classAnnotations = thisJoinPoint.getThis().getClass().getAnnotations();

String ArgumentValue = null;

for ( Annotation annotation : classAnnotations ) {

if ( annotation instanceof Anno1 ) {

ArgumentValue = ((Anno1) annotation).Argument();

break;

}

}

if ( ArgumentValue != null && ArgumentValue.equals("Option1")) {

z.invokeToAll();

}

}

其中thisJoinPoint是一个特殊的参考变量.

UPDATE2:

如果要在您的方面添加System.out.println(this),则需要在其中写入System.out.println(thisJoinPoint.getThis()),刚刚测试并可以正常工作. thisJoinPoint.getThis()返回你“这个”但不完全;实际上这是Object变量,如果你想获得任何属性,你需要投射或使用反射.而这个JoinPoint.getThis()不提供对私有属性的访问.

嗯,现在好像你的问题已经回答了,但是如果我错过任何东西,或者你以这种方式获得更多的问题/问题,请随时问;)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值