Search code examples
intellij-idea

Intellij structured search classes without fields


Utility classes don't have state, and so don't have fields. I want to find all utility classes in my code that are being instantiated.

I've added a private no-args constructor to all utility classes I know about, but there are some written before my time. I just found one and I want to find the others. Can structured search and replace show these?

EDIT

The image shows my best attempt at an SSR for this problem.

enter image description here

I thought that setting the count on $Field$ to [0,0] would ensure all classes with public constructors and no fields are found, but instead the search returns methods with fields e.g.

public class HTTPAuthenticationRequest implements InternalMsg {

  protected String echoData;

Solution

  • Try using a template like this:

    <searchConfiguration name="Potential Utility Classes" text="class $X$ extends $N$ implements $M$ {&#10;  public $X$();&#10;  $Type$ $field$;&#10;}" recursive="true" type="JAVA" pattern_context="default" search_injected="false">
      <constraint name="__context__" within="" contains="" />
      <constraint name="X" within="" contains="" />
      <constraint name="Type" within="" contains="" />
      <constraint name="field" minCount="0" maxCount="0" within="" contains="" />
      <constraint name="N" minCount="0" maxCount="0" within="" contains="" />
      <constraint name="M" minCount="0" maxCount="0" within="" contains="" />
    </searchConfiguration>
    

    (Use the Import Template from Clipboard button in the toolbar above the Existing Templates panel)

    And IntelliJ IDEA has inspections built in to find some of these problems. Use the following inspections:
    Instantiation of utility class (in the Java | Probable bugs catogory)
    and
    Utility class without 'private' constructor (in the Java | Class structure catogory)

    You can run these on your entire project using Code | Analyze | Run Inspection by Name for example.