简体   繁体   中英

Is there a way to use annotations to build a java class, based on the properties of multiple java classes?

There is a way to use annotations to build a java class, based on the properties of multiple java classes?

I want to create a generic log history table for all operations and entities in a spring data jpa project, for this i was thinking if would be possible to get all properties of my entities at compilation time to generate this generic entity log class.

I don't know so much about annotations, but it is used to generate source files so i believe that isn't a impossible ideia.

Could someone give some direction? If it's possible would be nice to point me a good starting point. Or if there is something already done that match my intent.

Annotations themselves do not generate source files -- they signify pointcuts for other classes to enhance/enrich them, or as a marker interface.

However, you can definately use an annotation scanner to scan files and get all the fields. Then what is left is generating a class from this. (and then, compile it). Be aweare that this is a multi-step process, and it may seem a bit clunky: you create a file with name GenericEntity , make sure it's in the proper package (so start it with package my.fun.project , write the imports, and write the java class, all as strings which you send tot he file. From you scan you have an annotated field / class and you can get the type and name (see the reflections library if necessary), and write that to your file as well. Then close the class properly with a } . Now it should a file which should not give compilation errors when loaded in your IDE. This GenericEntityGenerator then has to be executed (using a maven plugin, probably) on your source code, probably during the generate-sources phase, after which your generated ZA2F2ED4F8EB C2CBB4C21A29DC40AB61DZ will be compiled during the compile phase.... and bob's your uncle now.

In all, a fun project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM