I am trying find how to implement a hack that is similar to the Eclipse functionality "Add unimplemented methods".
Instead of adding these methods while writing code, I would like to do this during compilation , generating a method body using a template. Further, I do not want to modify the original .java source file.
For example, say I have the following:
interface I { void foo(); }
class C implements I {
public static void main(String[] args) { new C().foo(); }
}
Compiling this will usually result in error because I.foo
is not implemented.
I would like instead for compile to succeed and subsequent execution to use my template. The template could be something as simple as {throw UnsupportedOpeationException()
} I do want to be able to get more information about the method and the implemented interface and use it in the template, but that should not be difficult?
My first thought was to try an annotation (AutoImplementMethods
) but the annotation processor cannot modify the annotated code it is processing.
I am somewhat comfortable with AspectJ
but I don't see how it be done using inter-type declarations.
Any suggestions how this can be done, short of using my own java parser and generating code code?
Look at project lombok, as Lombok does something similar to what you want.
Lombok will take this source,
public class GetterSetterExample {
@Getter @Setter private int age = 10;
@Setter(AccessLevel.PROTECTED) private String name;
@Override public String toString() {
return String.format("%s (age: %d)", name, age);
}
and generate a class like,
public class GetterSetterExample {
private int age = 10;
private String name;
@Override public String toString() {
return String.format("%s (age: %d)", name, age);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
protected void setName(String name) {
this.name = name;
}
}
Lombok uses the JSR 269 Pluggable Annotation Processing API.
There is an article describing how lombok works here, and how to add your own transformation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With