简体   繁体   English

Java在运行时编辑注释属性

[英]Java editing annotation attributes at runtime

Is there a way modify the attributes of Field annotations at runtime? 有没有办法在运行时修改字段注释的属性? Not just the annotation object you can get from a Field at any one point, but whenever in the future you get the same annotation it is updated with the new values. 不仅您可以随时从字段中获取注释对象,而且将来在任何时候获得相同注释时,都会使用新值对其进行更新。

My task is to be able to at runtime compile a Java file and then use that Class in the application. 我的任务是能够在运行时编译Java文件,然后在应用程序中使用该Class。 I've done that, but the only problem is that while in a standard Java application custom annotations do get saved, they are for some reason stripped when run on a Spring application running on Tomcat 7. This is all in memory compilation BTW, no files are ever created in the process. 我已经做到了,但是唯一的问题是,尽管在标准Java应用程序中确实保存了自定义注释,但是由于某些原因,在运行于Tomcat 7的Spring应用程序上运行时,它们由于某种原因而被剥离了。文件是在此过程中创建的。

I couldn't find any way to solve that issue, so I decided to just parse the Java file a second time and add annotations to whatever fields I needed to. 我找不到任何解决该问题的方法,所以我决定再次解析Java文件,并在需要的任何字段中添加注释。 I figured out how to add an annotation to a field which didn't have any before through some hacks, but now I need to configure it, seeing as the annotation has some attributes, several booleans and an int. 我想出了如何通过一些技巧将注释添加到以前没有任何字段的字段,但是现在我需要对其进行配置,因为注释具有一些属性,几个布尔值和一个int。

I've looked into several ways provided in a lot of StackOverflow questions, but they all modify the annotation object that you obtain through reflection, and if I in another method try to get the same annotation, it's values are reset. 我研究了许多StackOverflow问题中提供的几种方法,但是它们都修改了通过反射获得的注释对象,如果我用另一种方法尝试获取相同的注释,则会重置其值。 Any insight into the matter would be greatly appreciated. 任何对此事的见识将不胜感激。

For anyone viewing this in the future, I solved the problem by first compiling my code and getting the bytecode before it is created into a class. 对于以后看到此内容的任何人,我都通过首先编译我的代码并在创建字节码之前将其获取到类中来解决该问题。 Then I used Javassist to add annotations at runtime. 然后,我使用Javassist在运行时添加注释。 After that I just compiled it into a class through a custom class loader, which got me the Class object without loading it into the system class loader. 之后,我通过一个自定义的类加载器将其编译为一个类,这使我获得了Class对象,而没有将其加载到系统类加载器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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