开发者

How to generate getters en mass using aspectj

I have the following problem, I am wondering whether anyone knows a solution:

I would like to dynamically generate specially named getters for every private field in every subclass of a certain class using aspectj or some other similar bytecode manipulation tool.

I would like the names of the getters to be based on the corresponding field names, but I can settle for having one method taking a field name string and returning a value, as long as there is开发者_JAVA技巧 no reflection involved.


Have you looked into Lombok? If you have access to the source and are just trying to save typing, than its @Data annotation might be what you looking for.


As in Matt's answer, I suggest you Lombok. Using the @Getter, @Setter annotations on the class level, corresponding getters/setters based on names of all the non-static fields will be generated at compilation.

Much better than annotating classes by hand is to use static crosscutting of AspectJ (page in the official documentation) to add those annotations globally.

Example for declaring @Getter and @Setter on each persistent Entity :

import javax.persistence.Entity;
import lombok.Getter;
import lombok.Setter;

public aspect EntityAspect {
    declare @type: @Entity * : @Getter;
    declare @type: @Entity * : @Setter;
}

It requires you either to have the source code, or to use compilation by aspectj on existing jar (instrumentation of an existing library).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜