Force Eclipse to automatically import a class with

2019-03-22 18:55发布

问题:

If a class is used in a Java project in Eclipse, and it's not imported already, and there is only one class with that name, Eclipse will automatically import it.

If there are two or more classes with the same simple name, Eclipse will ask the user to select the desired one. I would like to avoid having to select one and instead prefer having a default class imported.

For example, I commonly use List and ArrayList. And each time I use them in a new class, I have to select java.util.ArrayList and java.util.List from the suggestions of Eclipse, because there is another class with the name List (java.awt.List).

Is there some way to set java.util.List and java.util.ArrayList as a default import if List and ArrayList is used?


For now, I created an Eclipse template that triggers on the word List. Are there any other ideas or improvements?

${:import(java.util.List,java.util.ArrayList)}
List<> list = new ArrayList<>();

回答1:

If you don't use AWT in the project you can limit your accessible API like I mentioned in my blog: http://blog.firdau.si/2010/07/07/limit-your-access-to-java-api-for-more-productivity/

Works like a charm for me!



回答2:

You can also use the "Type Filters" from the Eclipse Preferences menu. This allows you to 'forbid' java.awt.* for all of your projects rather than just one.

Java -> Appearance -> Type Filters (or search for "Type Filters")



回答3:

Either you can add "Access Rules" on your project's properties or (this seems even better if you for example won't need java.awt.List at all) Go to your workspace's Preferences,

Java->Appearance->Type Filters (or search for "Type Filters")

And add your classes and packages to be ignored here