Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default imports in Eclipse

Tags:

java

eclipse

Is there a way to customize the default imports in Eclipse?

For example if I open a new JUnit Test Class by default I get these imports:

import static org.junit.Assert.*;
import org.junit.Test;

What I'd like to get:

import static org.junit.Assert.*;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
like image 274
harel Avatar asked Feb 18 '15 11:02

harel


People also ask

How do I get all imports in Eclipse?

Press: CTRL + SHIFT + O and you should see below dialog boxes. Choose your desired import package and click next. It will prompt you for your next import and thats it. You are done.

Does Eclipse auto import?

In above situation, Eclipse comes with a nice feature called “Organize Imports” to imports all the classes that are used, automatically. A copied source code without imports.

What is the order of imports in Java?

import statements should be sorted with the most fundamental packages first, and grouped with associated packages together and one blank line between groups. The import statement location is enforced by the Java language.


1 Answers

Unfortunately, Eclipse is quite lacking in the customizability of code generation when refactoring and creating new entities.

You might want to check out Eclipse Optimize Imports to Include Static Imports for information how to make content assist find static methods in predefined classes. That might be what you actually want. In the accepted answer Joey Gibson writes that you can add org.hamcrest.Matchers to Window » Preferences » Java » Editor » Content Assist » Favorites.


Another solution to the specific problem of statically importing Hamcrest methods, is to configure a Code Template named hamcrest instead. That way you can simply type ham and follow up with ctrl + space to get the import at the top.

The template should look like

${staticImport:importStatic('org.hamcrest.Matchers.*')}${cursor}

An even more convenient hack is to add this template to the already existing test code template which generates a new test method. If you change this template to:

@${testType:newType(org.junit.Test)}
public void ${testName}() throws Exception {
    ${staticImport1:importStatic('org.hamcrest.Matchers.*')}
    ${staticImport2:importStatic('org.junit.Assert.*')}${cursor}
}

and use this each time you make a new test method you will never have to care about adding the hamcrest import manually again.

Image to show where you configure it: hamcrest code template

like image 197
K Erlandsson Avatar answered Sep 23 '22 16:09

K Erlandsson