diffplug / diffplug/spotless

expandWildcardImports: necessary imports in method call expressions removed

Open
#2,833 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
5.6k
Forks
559
Avg merge
1d 13h
Merged PRs (30d)
34

Description

## Issue

The new `expandWildcardImports` step removes necessary imports in method call expressions, e.g.:

```java
import com.alibaba.fastjson.*;
public class Demo {
public static void main() {
final JSONObject jsonObject = new JSONObject();
final Script inlineScript = JSON.toJSONString(jsonObject);
}
}
```

becomes

```java
import com.alibaba.fastjson.JSONObject;
public class Demo {
public static void main() {
final JSONObject jsonObject = new JSONObject();
final Script inlineScript = JSON.toJSONString(jsonObject);
}
}
```

The import `import com.alibaba.fastjson.JSON` is missing and the code fails to compile.

## Java version

```
openjdk 25.0.1 2025-10-21
OpenJDK Runtime Environment (build 25.0.1+8-Ubuntu-125.10)
OpenJDK 64-Bit Server VM (build 25.0.1+8-Ubuntu-125.10, mixed mode, sharing)
```

## Solution

Code like `JSON.toJSONString(jsonObject)` seems to be a method call expression:

https://github.com/diffplug/spotless/blob/8e776ec835b443b2c7d7e9e662aac268fa270050/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ExpandWildcardsFormatterFunc.java#L181-L188

The current code above only checks the method (`toJSONString`), but not the scope of the method. Adding this resolved the issue for me:

```java
n.getScope().ifPresent(s -> {
ResolvedType type = n.getSymbolResolver().calculateType(n.getScope().get());
if (type != null && type.isReference()) {
matchTypeName(importMap, type.asReferenceType().getQualifiedName(), false);
}
});
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.