简体   繁体   English

如何从Groovy AST转换访问所有构造函数?

[英]How can I access all constructors from a Groovy AST transformation?

I am writing an AST transformation intended to keep a bidirectional JPA relationship in sync by making the setter on the referenced side also call the setter on the owning side. 我正在编写AST转换,旨在通过使引用方的设置程序也称为拥有方的设置程序来保持双向JPA关系的同步。 This works reliably when calling setFoo() , but a variable initialized in the constructor (because of a initializer statement in the declaration, a new in the constructor, or a constructor parameter) won't be linked. 这在调用setFoo()时可靠地setFoo() ,但是不会链接在构造函数中初始化的变量(由于声明中的初始化程序语句,构造函数中的new或构造函数参数)。

To handle this case, I can open up all of the existing constructors (plus any implicit default constructor) and add the necessary code. 为了处理这种情况,我可以打开所有现有的构造函数(加上任何隐式默认构造函数)并添加必要的代码。 However, some common AST transformations that add constructors, such as @TupleConstructor , run in the CANONICALIZATION phase, and there's no phase after that where I can reliably insert new instructions. 但是,一些常见的添加构造函数的AST转换(例如@TupleConstructor )在CANONICALIZATION阶段运行,此后没有阶段可以可靠地插入新指令。

How can I ensure that my extra code is added to each constructor, including ones that may be added by other transformations? 如何确保将我的额外代码添加到每个构造函数中,包括可能由其他转换添加的代码?

The best approach here isn't to alter all the constructors but rather to use an object initializer block, which is copied to the end of all constructors. 最好的方法不是更改所有构造函数,而是使用对象初始化程序块,该块被复制到所有构造函数的末尾。 There's a minor unsafe-publication risk if the cooperating class does something foolish, but it's the same risk as adding the statement to the end of constructors explicitly. 如果合作类做一些愚蠢的事情,则存在较小的不安全发布风险,但这与将语句显式添加到构造函数末尾的风险相同。

The way to do this is: 这样做的方法是:

classNode.addObjectInitializerStatements(assignS(target, value));

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

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