GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add shortenFullyQualifiedTypes step (fixes #2945) by maxandersen · Pull Request #3005 · diffplug/spotless

Conversation

@maxandersen

@maxandersen maxandersen commented Jul 31, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

headsup - I used llm to generate this; first time contributing to this area but did a quick read and seemed to match similar operations and been using it in my own workflows so it at least works for my usecases :)

Summary

Adds a new Java formatter step that replaces fully qualified type names with simple names and adds the required imports. Designed to clean up LLM-generated code and other sources that use inline FQNs unnecessarily.

Before

public class UserService {
    private final java.util.Map<String, java.util.List<String>> cache = new java.util.HashMap<>();
    public java.util.List<String> getUsers(java.util.function.Predicate<String> filter) throws java.io.IOException {
        java.util.List<String> result = new java.util.ArrayList<>();
        return result;
    }
}

After

import java.io.IOException;
import java.util.*;
import java.util.function.Predicate;

public class UserService {
    private final Map<String, List<String>> cache = new HashMap<>();
    public List<String> getUsers(Predicate<String> filter) throws IOException {
        List<String> result = new ArrayList<>();
        return result;
    }
}

Implementation

  • Uses JavaParser for AST-based type identification (no regex false positives from strings, comments, or non-type contexts)
  • Position-based text replacement preserves original formatting exactly
  • Configured with BLEEDING_EDGE language level to support Java 14–25 syntax
  • Deduplicates AST visits (JavaParser visits instanceof pattern nodes twice)

Safety

Skips rewriting when:

  • Two different FQNs map to the same simple name (conflict)
  • An existing import already claims the simple name for a different type
  • The file can't be parsed (returns input unchanged)
  • java.lang.* types (shortened without import)
  • Same-package types (shortened without import)

Usage

Gradle:

spotless {
    java {
        shortenFullyQualifiedTypes()
        importOrder()
        removeUnusedImports()
    }
}

Maven:

<java>
    <shortenFullyQualifiedTypes/>
    <importOrder/>
    <removeUnusedImports/>
</java>

Tests

16 tests covering: basic shortening, conflict detection, existing import conflicts, java.lang handling, same-package handling, idempotency, and Java 14–25 syntax (instanceof patterns, switch patterns, records, sealed classes, text blocks, var+generics, lambda casts).

Fixes #2945

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

omatheusmesmo, pdudits, mukel, jonesbusy, ayagmar, anyulled, jamaly87, omarmahamid, w0rxbend, jcputney, and shamil0xff reacted with thumbs up emoji
All reactions
  • 👍 11 reactions
@maxandersen
Add shortenFullyQualifiedTypes step (fixes diffplug#2945)
3f747df
Adds a new Java formatter step that replaces fully qualified type names
with simple names and adds the required imports. For example:

    java.util.List<String> items = new java.util.ArrayList<>();

becomes:

    import java.util.List;
    import java.util.ArrayList;
    ...
    List<String> items = new ArrayList<>();

Uses JavaParser for AST-based type identification — no false positives
from strings, comments, or non-type contexts. Position-based text
replacement preserves original formatting.

Safety: skips when simple names conflict (two FQNs → same short name),
when an existing import claims the name for a different type, and when
the file can't be parsed. java.lang and same-package types are shortened
without adding imports.

Tested with Java 14–25 syntax: instanceof pattern matching, switch
patterns, records, sealed classes, text blocks, var with generics,
and lambda casts (16 tests).

Wired into both Gradle (shortenFullyQualifiedTypes()) and Maven
(<shortenFullyQualifiedTypes/>), designed to run before importOrder()
and removeUnusedImports().

New files:
- lib/.../java/ShortenFullyQualifiedTypesStep.java (step class)
- lib/.../glue/javaparser/ShortenQualifiedTypesFormatterFunc.java (glue)
- plugin-maven/.../java/ShortenFullyQualifiedTypes.java (Maven factory)
- testlib/.../java/ShortenFullyQualifiedTypesStepTest.java (16 tests)

Modified:
- plugin-gradle/.../JavaExtension.java (+shortenFullyQualifiedTypes())
- plugin-maven/.../java/Java.java (+addShortenFullyQualifiedTypes())
@maxandersen

maxandersen commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

Any luck to get this reviewed/merged ?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@nedtwigg
Merge remote-tracking branch 'origin/main' into removeFullyQualifiedN…
ded9559
…ames
@nedtwigg

nedtwigg commented Aug 15, 2026

Copy link
Copy Markdown
Member

This looks great! It needs changelog entries (3 of them), and also an entry in the root README.md listing of steps (note that there is a magic markdown comment that generates the table).

jamaly87 reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

nedtwigg and others added 6 commits August 16, 2026 15:45
@nedtwigg
Merge remote-tracking branch 'origin/main' into removeFullyQualifiedN…
13ee27e
…ames
@nedtwigg @claude
docs: changelog entries and README matrix row for shortenFullyQualifi…
b395fd1
…edTypes

Adds the three changelog entries (lib, plugin-gradle, plugin-maven) and a
row in the root README's freshmark-generated feature matrix, updating both
the freshmark source block and the generated table.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@nedtwigg @claude
docs: document shortenFullyQualifiedTypes in the plugin READMEs
cd57b58
Adds a section to plugin-gradle/README.md and plugin-maven/README.md next
to the other import-management steps, with a before/after example and the
cases where a name is deliberately left fully-qualified. Also lists the
step in each plugin's main Java config block, ahead of importOrder, since
new imports are appended unsorted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@nedtwigg @claude
docs: list the Java import steps in the plugin README tables of contents
1c5bc0a
The Java TOC line in both plugin READMEs listed the formatters but none of
the import-management steps. Adds shortenFullyQualifiedTypes along with the
four that were already undocumented in the TOC: removeUnusedImports,
forbidWildcardImports, expandWildcardImports, and forbidModuleImports.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@nedtwigg @claude
chore: spotlessApply
0c49e65
Removes two unused imports (java.util.Optional, StepHarness), updates the
copyright headers to 2025-2026, and applies the project's eclipse format
to the new files.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@nedtwigg
Better place to put the shortenFullyQualifiedTypes docs
45bea6d
@nedtwigg

nedtwigg commented Aug 16, 2026

Copy link
Copy Markdown
Member

I wanna publish a new version today so I'll make the changes above myself. Didn't realize how much demand for this feature there was!

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

nedtwigg and others added 2 commits August 16, 2026 16:56
@nedtwigg
Better organization on the changelogs.
4430823
@nedtwigg @claude
fix: make the FQN-collecting visitor a named static class
6b42c5e
SpotBugs (SIC_INNER_SHOULD_BE_STATIC_ANON) failed :lib:spotbugsJavaParser
because the anonymous VoidVisitorAdapter captured the enclosing
ShortenQualifiedTypesFormatterFunc instance without ever using it. Lift it
into a named static class taking its state as constructor args, matching
ExpandWildcardsFormatterFunc.CollectImportedTypesVisitor.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@nedtwigg
nedtwigg merged commit 8b57c01 into diffplug:main Aug 17, 2026
20 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@maxandersen

maxandersen commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

I wanna publish a new version today so I'll make the changes above myself. Didn't realize how much demand for this feature there was!

appreciated. sorry for missing pings - just happy its now in! :)

nedtwigg reacted with heart emoji
All reactions
  • ❤️ 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@maxandersen maxandersen mentioned this pull request Aug 23, 2026
shortenFullyQualifiedTypes: skip FQNs whose simple name clashes with types declared in the same file #3031
Merged
Marcono1234
Marcono1234 reviewed Sep 14, 2026
View reviewed changes
Comment thread testlib/src/test/java/com/diffplug/spotless/java/ShortenFullyQualifiedTypesStepTest.java
Comment on lines +304 to +315
@Test
void multipleAnnotationsWithFqn() throws Exception {
// FQNs used as annotation types should NOT be treated as type references
// (annotations start with @, not handled by ClassOrInterfaceType)
// but FQN types in annotation values or alongside annotations should work
String before = String.join("\n",
"package com.example;",
"",
"public class Foo {",
" java.util.List<String> items;",
"}",
"");

@Marcono1234 Marcono1234 Sep 14, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this test here correct? The name and the comments talk about annotations, but the example code does not actually contain any annotations.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@maxandersen maxandersen mentioned this pull request Oct 6, 2026
shortenFullyQualifiedTypes corrupts method references on fields (x.field::m -> bogus import x.field) #3133
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

1 more reviewer
@Marcono1234 Marcono1234 Marcono1234 left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Add formatter step to shorten unnecessary fully qualified class names

Uh oh!

There was an error while loading. Please reload this page.

3 participants

@maxandersen @nedtwigg @Marcono1234
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.