开发者

Getting initializer in annotated field

Let's say I have thi开发者_开发百科s class:

@Annotate class MyClass { MyField field = new MyField(params); }

How can I get the initializing part of my class field when I process my annotation (the new MyField(params) part)?

I can't see anything related in the FieldDeclaration class.


You can't.

Whether you use reflection or apt, you cannot access code blocks.

  • Through apt you can access anything you can annotate, but you can't annotate initializer blocks (although you could access an annotated local variable inside an initializer block).
  • Through reflection there is no way to access code blocks (only Constructors, Fields, Methods and Classes)

If you are desperate enough about this, you need to use a source parser like javaparser or a byte code tool like asm. Both understand tree structures (the former uses source trees, the latter byte code trees) and can deal with all java structures, including initializer blocks.

But your best bet is probably AspectJ and it's initialization(ConstructorSignature) pointcut. There is some reference on the pointcuts page but to really grasp it you would probably have to read AspectJ in Action by Ramnivas Laddad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜