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.*;
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With