Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

java - Can I add a method to a class from a compile time annotation?

If I create a custom annotation (example: @SaveFuncName("saveMe") will add a method called saveMe() with some code my processor generates), can the javac compiler use my annotation processor to add a method to the class? Or can I only create a different class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Or can I only create a different class?

That's correct. The existing API doesn't let us modify existing classes, just generate new ones.

Technically speaking, if you want to do some hacky stuff, it's possible to use internal Javac API to modify the abstract syntax tree directly but it's not for the faint of heart. For example, an object like TypeElement is actually a symbol directly from Javac, hidden from us by the interface. The syntax tree is also available in a read-only mode through the compiler tree API. We can cast the interfaces away and modify the code that way. This is how e.g. Project Lombok works.

(But I can't recommend doing this. I'm mostly explaining it because Lombok is a thing that exists so it looks like modifying classes is possible.)

The easiest solutions are to do something like generate a superclass with e.g. saveMe() methods and extend it or generate a utility class and delegate to it. (Also suggested here.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...