1

Let's say I have this 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.

1
  • You want to access the source code (.java), given the compiled code (.class)? Commented Jan 14, 2011 at 13:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.