如何在IntelliJ中使用结构化搜索和替换将Java泛型声明转换为仅在局部作用域中的var声明?

daupos2t  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(90)

我尝试使用IntelliJ中的结构化搜索和替换模板创建一个检查,它将泛型声明转换为仅在局部作用域中的var声明。例如,我想转换如下代码:

Map<String, List<String>> myVar = new ConcurrentHashMap<>(10, 2);

致:

var myVar = new ConcurrentHashMap<String, List<String>>(10, 2);

我已经创建了一个匹配泛型声明的搜索模板和一个替换模板,替换模板用var声明替换它,我还添加了一个脚本约束,将搜索和替换限制在局部范围内:

检索:$Type$<$GenericArgument$> $Var$ = new $Ctor$<>($Params$);
替换:var $Var$ = new $Ctor$<$GenericArgument$>($Params$);
完全更换配置:

<replaceConfiguration name="replace with var" text="$Type$&lt;$GenericArgument$&gt; $Var$ = new $Ctor$&lt;&gt;($Params$);" recursive="false" caseInsensitive="true" type="JAVA" pattern_context="default" reformatAccordingToStyle="true" shortenFQN="true" useStaticImport="true" replacement="var $Var$ = new $Ctor$&lt;$GenericArgument$&gt;($Params$);&#10;">
   <constraint name="__context__" script="&quot;__context__.getParent() instanceof com.intellij.psi.PsiCodeBlock&quot;" within="" contains="" />
   <constraint name="Type" within="" contains="" />
   <constraint name="GenericArgument" minCount="0" maxCount="2147483647" within="" contains="" />
   <constraint name="Var" within="" contains="" />
   <constraint name="Params" minCount="0" maxCount="2147483647" within="" contains="" />
   <constraint name="Ctor" within="" contains="" />
</replaceConfiguration>

然而,当我运行结构化搜索和替换时,生成的代码在泛型参数之间缺少逗号:

var myVar = new ConcurrentHashMap<String List<String>>(10, 2);

如何修改搜索和替换模板以在泛型参数之间包含逗号?

gcuhipw9

gcuhipw91#

这似乎是一个错误,我已经提交了an issue
您可以通过在替换模板中使用替换变量来解决此错误。替换变量上的脚本可以从完整类型计算正确的类型参数。该脚本如下所示:

def x = Type.getInnermostComponentReferenceElement().getParameterList().getText()
x.substring(1, x.length() - 1)

它获取类型并检索其类型参数列表,将其转换为文本,然后截断<>
以下是完整配置:

<replaceConfiguration name="replace with var" text="$Type$&lt;$GenericArgument$&gt; $Var$ = new $Ctor$&lt;&gt;($Params$);" recursive="false" type="JAVA" pattern_context="default" search_injected="false" reformatAccordingToStyle="true" shortenFQN="false" replacement="var $Var$ = new $Ctor$&lt;$GenericArgument2$&gt;($Params$);&#10;">
  <constraint name="__context__" script="&quot;__context__.getParent() instanceof com.intellij.psi.PsiCodeBlock&quot;" within="" contains="" />
  <constraint name="Type" within="" contains="" />
  <constraint name="GenericArgument" minCount="0" maxCount="2147483647" within="" contains="" />
  <constraint name="Var" within="" contains="" />
  <constraint name="Params" minCount="0" maxCount="2147483647" within="" contains="" />
  <constraint name="Ctor" within="" contains="" />
  <variableDefinition name="GenericArgument2" script="&quot;def x = Type.getInnermostComponentReferenceElement().getParameterList().getText()&#10;x.substring(1, x.length() - 1)&quot;" />
</replaceConfiguration>

相关问题