Use IntelliJ structural search to replace a field and express it with a new field

I want to use ButterKnife for Android. I need to annotate some fields based on some expressions that are located elsewhere in the code. I have a code like this

private String myField; ... public myClassConstructor() { ... myField = res.getString(R.string.my_string_id); ... } 

I want this

 @BindString(R.string.my_string_id); String myField; ... public myClassConstructor() { ... ... } 

As a result, the expression disappears, and the field is annotated based on the old expression.

Is it possible to perform such a search and replace in IntelliJ structural replacement? It seems that he does not gracefully handle the case when the lines of interest are not adjacent and are in different places structurally. I tried to base it on a class template and used $ Statement $ (0-unlimited occurrences), but this did not work for me.

I realized that it is relatively easy to use with regular expressions, which is much simpler than searching for IntelliJ's structural search for ball games, but I like to study my tools, so I would like to know if this is possible.

+5
source share
2 answers

While Search structurally somehow works and a search query can be made, replace structuraly is a tool created by aliens for predators. I hope that the intelliJ team will revise this function and make it more convenient and understandable.

I tried to make the Replace structurally query Replace structurally myself, but I could only do the Search structurally sentence.

I did this with the Mockito lib, for example.

Structural Search Dialog

One of the key points here is to set for $SomeStatement1$ and $SomeStatement2$ min and max count to {0, Unlimited}

enter image description here

And from that moment I tried to come up with a replacement proposal, but it completely destroyed the description area / class of the method / fields.

Hope this helps.

+2
source

Something like this should work.
Search Pattern:

 class $Class$ { $FieldType$ $FieldName$; $Class$() { $st1$; $FieldName$ = res.getString($expr$); $st2$; } } 

Variables:
st1 min: 0 max: unlimited
st2 min: 0 max: unlimited

Spare Template:

 class $Class$ { @BindString($expr$) $FieldType$ $FieldName$; $Class$() { $st1$; $st2$; } } 
0
source

Source: https://habr.com/ru/post/1241723/


All Articles