Skip to content

Replace static imports with non-static imports #1379

Closed

Description

@szpigielm

Hi is it possible to setup spotless to replace static imports with non-static imports in Java?

Example:

Static import:

import static org.enums.Value.SOME_ENUM_VALUE;

public class Test {
    public void method() {
        var example = SOME_ENUM_VALUE;
    }
}

Replace with

import org.enums.Value.SOME_ENUM_VALUE;

public class Test {
    public void method() {
        var example = Value.SOME_ENUM_VALUE;
    }
}

Activity

  1. changed the title [-]How to replace static imports with non-static imports?[/-] [+]Reeplace static imports with non-static imports[/+] on Oct 19, 2022
  2. nedtwigg commented on Oct 19, 2022

    @nedtwigg
    Member

    This is not possible right now, but we'd be happy to merge a PR which added support for this.

  3. changed the title [-]Reeplace static imports with non-static imports[/-] [+]Replace static imports with non-static imports[/+] on Oct 19, 2022
  4. Chasson1992 commented on Dec 30, 2022

    @Chasson1992

    @szpigielm I was going to implement this since I would be intersted in using this as well.

    I was going to add to the Java extension a function called replaceStaticImports to enable this formatting.

    spotless {
      java {
        replaceStaticImports()
      }
    }
    

    The basic case is straight forward.

    Instead of

    import static org.junit.jupiter.api.Assertions.assertTrue;
    ...
        assertTrue(true)
    ...
    

    Replace with

    import org.junit.jupiter.api.Assertions;
    ...
        Assertions.assertTrue(true)
    ...
    

    The more complicated case would be with wildcard imports, in order for that to work we would need access to the compilation classpath which is beyond the scope of most formatters.

    Any suggestions on how to handle the wildcard static imports?

  5. nedtwigg commented on Dec 30, 2022

    @nedtwigg
    Member

    In this place

    protected void setupTask(SpotlessTask task) {
    if (target == null) {
    JavaPluginConvention javaPlugin = getProject().getConvention().findPlugin(JavaPluginConvention.class);
    if (javaPlugin == null) {
    throw new GradleException("You must either specify 'target' manually or apply the 'java' plugin.");
    }
    FileCollection union = getProject().files();
    for (SourceSet sourceSet : javaPlugin.getSourceSets()) {
    union = union.plus(sourceSet.getAllJava());
    }
    target = union;
    }
    steps.replaceAll(step -> {
    if (isLicenseHeaderStep(step)) {
    return step.filterByFile(LicenseHeaderStep.unsupportedJvmFilesFilter());
    } else {
    return step;
    }
    });

    You have:

    • the java plugin
    • you can replace a StaticImportStep that doesn't have the classpath with a new StaticImportStep which does have the classpath

    so that should be everything you need. I'm not sure how to make it work with maven, but it's fine to have features which only work for one plugin or another.

  6. agreedSkiing commented on Jan 27, 2023

    @agreedSkiing

    Would this be possible to do in the maven plugin if the dependecy for org.eclipse.jdt.ls.core is included since it has a helper method that does this? https://github.com/eclipse/eclipse.jdt.ls/blob/master/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/cleanup/StaticAccessUsesClassNameCleanUp.java

    It atleast works in VSCode when having the qualifyStaticMembers identifier set in the redhat.java VSCode plugin

    import static org.junit.jupiter.api.Assertions.*;
    
    public class Test { 
    @Test
      public void fake_test() {
        assertTrue(true);
        assertFalse(true);
      }
    }

    to

    import static org.junit.jupiter.api.Assertions.*;
    import org.junit.jupiter.api.Assertions;
    
    public class Test { 
    @Test
      public void fake_test() {
        Assertions.assertTrue(true);
        Assertions.assertFalse(true);
      }
    }
  7. agreedSkiing commented on Jan 27, 2023

    @agreedSkiing
  8. nedtwigg commented on Jan 27, 2023

    @nedtwigg
    Member

    Would this be possible to do in the maven plugin

    It's definitely possible. The trouble is that currently Spotless provides only source code to the formatters. It does not provide compiled jars or the classpath.

    Normally people can add a FormatterStep to Spotless and making it work in the build plugins is very little work. In this case, the classpath will have to piped from the build plugin to the FormatterStep, which we have never done before. I know how to do that in the Gradle plugin (shown above), and it can certainly be done in Maven, I just don't know how.

    Once someone has done it once, we'll be able to standardize it and make it easier to make other classpath-dependent steps in the future.

  9. Chasson1992 commented on Jan 27, 2023

    @Chasson1992

    I have the classpath access working with Gradle, I just need to implement the FormatterStep logic. Grad school classes started again so I'm a little crunched for time.

    Like Ned, I don't have any experience with the Maven API but I have a lot of experience with the Gradle API. If there's someone that knows how to get the classpath in Maven, I'd certainly add that to the PR.

  10. nedtwigg commented on Jan 27, 2023

    @nedtwigg
    Member

    Amazing @Chasson1992, thanks for getting something going! Don't worry about the Maven stuff at all, that should be a separate PR. From our root README.md Why are there empty squares?

    image

    Many projects get harder to work on as they get bigger. Spotless is easier to work on than ever, and one of the reasons why is that we don't require contributors to "fill the matrix". ... Once someone has filled in one square of the formatter/build system matrix, it's easy for interested parties to fill in any empty squares, since you'll now have a working example for every piece needed.

  11. patpatpat123 commented on Nov 16, 2026

    @patpatpat123
    Contributor

    A 2026 status update, since a few things have changed since this was last discussed:

    • The classpath blocker is solved. The problem described above was that Spotless never handed a formatter step the project's classpath, which you need to know what a bare max(...) or SECONDS refers to. expandWildcardImports added exactly that plumbing to both the Gradle and the Maven plugin in late 2025.
    • Error Prone doesn't cover this. It has no rule against static imports in general. Its BadImport check (on by default, as a warning) only qualifies a fixed list of generic names such as of, copyOf, valueOf, builder or INSTANCE, because the class name gives the reader context there. It can be pointed at whole classes with -XepOpt:BadImport:BadEnclosingTypes, but that runs as part of compilation, not as a formatter. Google Java Style is fine with single static imports too, so this stays a per-project preference, which seems a good fit for Spotless.
    • There's a PR now: Add a replaceStaticImports step for Java #3185 adds replaceStaticImports() for Gradle and <replaceStaticImports/> for Maven, with a way to keep some static imports (AssertJ's assertThat, say). It only replaces a static import when it can show the result still compiles and means the same thing; otherwise it leaves the import alone.

    Feedback on the PR is very welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions