IDEA插件开发:如何用GroovyPatterns匹配run方法入参map中service键对应值
解决方案
匹配逻辑说明
你遇到的问题本质是Groovy中run service: 'xxx', with: yyy的语法糖会将所有键值对封装为单个Map类型参数传入run方法,你要匹配的createAgreementItem是这个Map中键为service的Entry的值,而非方法的直接参数,因此需要调整匹配规则的层级结构。
可直接使用的匹配代码
import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyPatterns; import static org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyPatterns.*; GroovyPatterns.groovyLiteralExpression() // 匹配作为Map Entry值的字符串字面量 .withParent( groovyMapEntry() // 限制该Entry的key为固定字符串"service" .withKey(groovyLiteralExpression().withValue("service")) ) // 向上追溯父层级,确认该Map属于GroovyBaseScript的run方法的首个参数 .withAncestor(2, groovyArgumentList() .methodCallParameter(0, psiMethod() .withName("run") .definedInClass("org.apache.ofbiz.service.engine.GroovyBaseScript") ) );
如果匹配不生效,可以打开IDEA的PSI Viewer(路径:Tools → View PSI Structure)查看目标字符串节点的实际父层级,调整withAncestor的层级数即可。
GroovyPatterns使用技巧
GroovyPatterns是IntelliJ平台通用PsiPattern体系的Groovy语言实现,没有单独的专项文档,用法完全遵循IntelliJ平台PSI模式的通用逻辑:通过链式调用描述目标PSI节点的属性、父/子节点特征、上下文环境等匹配条件。
调试规则时优先用PSI Viewer定位目标节点的结构,再对应编写匹配条件,效率最高。
内容的提问来源于stack exchange,提问作者Gaetan
相关产品推荐
相关产品推荐

