Marged
Marged

Reputation: 10973

Have Eclipse automatically import classes statically

When I'm creating JUnit tests Eclipse takes care of importing assertEquals for me automatically.

In my current code I often write statements like these:

Arrays.stream(columns).collect(toCollection(ArrayList::new));

Eclipse complains about the missing toCollection():

The method toCollection(ArrayList::new) is undefined for the type ...

When I manually add import static java.util.stream.Collectors.toCollection; import at least this warning is gone. But I get a new warning:

The import java.util.stream.Collectors.toCollection is never used

So basically I have two questions:

If this matters: I use the current version of STS 4.4.1

Upvotes: 1

Views: 735

Answers (1)

david a.
david a.

Reputation: 5291

To have static methods imported in the same way as assertEquals, add their classes to the list at: Window -> Preferences -> Java -> Editor -> Content Assist -> Favorites.

Eclipse will then propose static methods of those classes when you start typing.

On the unused import: I do not see this behavior in my Eclipse. Instead, with import static java.util.stream.Collectors.toCollection; and some use of toCollection in my code, such as: ...collect(toCollection(ArrayList::new)), there is no warning.

Note: if toCollection is refered to with it's class, such as: ...collect(Collectors.toCollection(ArrayList::new)), then Eclipse produces a warning on the static import of toCollection. This is correct, as the import is indeed not used (instead, an import of the Collectors class is used to resolve the class and the method). Could that be the case?

Upvotes: 3

Related Questions