Skip to main content

JDK 1.6: Annotation Processing & Compiler Hack

2 replies [Last post]
parikh.vikas
Offline
Joined: 2013-03-25
Points: 0

Hello,

I am currently using JDK 1.6.0_23
For one of the requirement, I am going with annotation processing & compiler Hack using Tools.jar available as part of JDK.

I have refered a PDF - "The Hacker's Guide to javac (PDF) by David Erni and Adrian Kuhn (2008)
" suggested from page of - http://openjdk.java.net/groups/compiler/

My requirement is below ->

Origional Source:

public void someMethod() {
   [..]
}
Modified Source:

public void someMethod() {
   int items = new example.Product().getItems();
   [..]
}

Below is my code to generate the variable declaration -

private TreeMaker make; // fetch it from somewhere
JCNewClass newProduct = make.NewClass(null, List.<JCExpression>nil(), make.Ident(names.fromString("example.Product")), List.<JCExpression>nil(), null);
JCFieldAccess fieldAccess = make.Select(newProduct, names.fromString("getItems"));
JCMethodInvocation getTimeMethodInvocation = make.Apply(List.<JCExpression>nil(), fieldAccess, List.<JCExpression>nil());
expression = getTimeMethodInvocation;
JCVariableDecl itemsDeclaration = make.VarDef(modifiers,name,varType,expression);
System.out.println(itemsDeclaration); // this prints int items = new example.Product().getItems();

This itemsDeclaration, I am adding to a JCBlock of JCMethodDecl.

However code does not compile :(

If I make below changes - It does compile

1) JCNewClass newProduct = make.NewClass(null, List.<JCExpression>nil(), make.Ident(names.fromString("Product")), List.<JCExpression>nil(), null);
Product insteadof example.Product

2) Add belwo statement in the origional source code
import examle.Product;

What exactly am I missing here ???
The AST tree is diffcult to understand with minimum documentation & without much help on the interent.

I hope this is correct forum, for my query.
It will be a great help.

Regards,
Vikas Parikh

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kizipro57

I thinks with code would do the following.
public void someMethod() {
[..]
}
Modified Source:

public void someMethod() {
int items = new example.Product().getItems();
[..]
}
Create new.
1) Create a Ident from Symbol (ClassSymbol)
2) Create a JCField from Name

parikh.vikas
Offline
Joined: 2013-03-25
Points: 0

Hello Guys,

I have investigated myself on this & would like to share with you guys, so that any other developer do not have to invest precious time like I have done.

To create a New Class, you require a JCExpression.

Below would work, if class already has imported Product class.
make.Ident(names.fromString("Product"))

However, if class has not imported the Product class, then there are 2 options -

1) Create a Ident from Symbol (ClassSymbol)
2) Create a JCField from Name

I used a later approach.

Regards,
Vikas Parikh