简体   繁体   English

以编程方式修改Java源代码中的注释

[英]Programmatically modify annotation in Java source code

I am looking for a way to analyze the Java code and programmatically modify them, 我正在寻找一种分析Java代码并以编程方式修改它们的方法,

For example, the code may be like this: 例如,代码可能是这样的:

@FindBy(id = "login")    
WebElement btnLogin;

@FindBy(xpath = "//div/a")    
List<WebElement> aNodes;

and I'd hope to check every field that is annotated by @FindBy, and change the annotation @FindBy into @Synchronized. 我希望检查@FindBy注释的每个字段,并将注释@FindBy更改为@Synchronized。

that is: 那是:

@Synchronized
WebElement btnLogin;

@Synchronized
List<WebElement> aNodes;

Unlike the similar questions I found (they use javassist or ASM to modify the bytecode), these annotation will be removed at runtime, so I can only do it in source code level but not in the bytecode level. 与我发现的类似问题不同(它们使用javassist或ASM修改字节码),这些注释将在运行时删除,因此我只能在源代码级别执行此操作,而不能在字节码级别执行此操作。

So far, I have find qdox , but seems it can only analyze the code but cannot modify it. 到目前为止,我已经找到了qdox ,但是似乎它只能分析代码而不能修改它。

And I tried to write regex myself to solve it, but it seems a too much huge project. 我试图自己编写正则表达式来解决它,但这似乎是一个巨大的项目。

Any recommendations on this? 有什么建议吗?

The regular expression for this should be very simple 正则表达式应该非常简单

Match any line starting with 匹配任何以

"^@FindBy"

or, if you're worried about an odd (but valid) syntax (@FindBy(blah) protected void ..) 或者,如果您担心语法奇怪(但有效)(@ FindBy(blah)受保护的void ..)

"^@FindBy(.*)"

That said, you can also use your favorite IDE to do a search and replace manually (Eclipse, IntelliJ, or even emacs should be able to do this across all files), since you seem to be doing this statically 也就是说,您也可以使用自己喜欢的IDE进行搜索和手动替换(Eclipse,IntelliJ甚至emacs应该能够在所有文件中执行此操作),因为您似乎是在静态地执行此操作

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

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