0

Is there a way in an IntellJ Idea project that I can replace all calls to getClass() with the current class name + .class?

So for example replace:

class ClassName{
  public method(){
    Logger.logDebug(getClass(), "Some information")
  }
}

with

class ClassName{
  public method(){
    Logger.logDebug(ClassName.class, "Some information")
  }
}
Bas Leijdekkers
  • 23,709
  • 4
  • 70
  • 68
Maarten
  • 808
  • 1
  • 6
  • 17
  • 1
    There is a feature called structural search that you probably could use: https://www.jetbrains.com/help/idea/2016.3/structural-search-and-replace-examples.html – Magnilex Mar 01 '17 at 08:40
  • @Magnilex I know about the structurally search and replace, unfortunately, I am having difficulties creating the right templates. Any help would be appreciated. – Maarten Mar 01 '17 at 08:43
  • Please go through the link @Magnilex shared or the PDF at https://www.jetbrains.com/idea/docs/ssr.pdf and try out a few things and see if you face any issues. – Atul Mar 01 '17 at 09:16

1 Answers1

7

Try this Structural Search template:

$This$.getClass()

Edit variables -> This -> Text/regexp: this, minimum count: 0, maximum count: 1

Replacement Template

$Clazz$.class

Edit variables -> Clazz -> Script text:

import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.PsiClass;
PsiTreeUtil.getParentOfType(__context__, PsiClass.class).getQualifiedName();

UPD: JetBrains support: This is currently not supported in the new Structural Search & Replace (SSR) dialog. It is possible to do this by going back to the old UI, here's how:

  1. Invoke Help | Find Action... (Ctrl/Cmd+Shift+A)
  2. Type Registry and invoke the Registry... action
  3. Remove the check mark for the ssr.use.new.search.dialog key and close the dialog

Now when you invoke SSR, you're back to the old dialog and can use replacement variables again. Restoring replacement variables for the new SSR dialog is planned for version 2019.2, but no guarantee.

komelgman
  • 6,949
  • 2
  • 18
  • 18
  • Exactly..., but, how are we supposed to find such an answer? Ow, wait, right, .... just ask Stack Overflow... Many thanks komelgman. – Maarten Mar 02 '17 at 15:18
  • Does this still work in IntelliJ 2018.x ? It always shows the error message ***"Malformed replacement pattern"*** when the replacement variables are not the same as the search variables. – walen Nov 28 '18 at 12:45
  • Vote for https://youtrack.jetbrains.com/issue/IDEA-204454 bug for speedup fixing it. – komelgman Mar 22 '19 at 15:01