December 30, 2015

How do you import static in Eclipse?

When you press Ctrl+Shift+O new imports are added and organized. But that will not work for static imports.

But if you place the cursor on the static import method and press Ctrl+Shift+M, then it will be imported.

Example

package se.magnuskkarlsson.example.timer;

import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

public class TimerTest {

    @Test
    public void test() throws Exception {
        Assert.assertThat("hello world", CoreMatchers.is(CoreMatchers.containsString("ell")));
    }
}

Now place cursor on each static method and press Ctrl+Shift+M and it will look like.

package se.magnuskkarlsson.example.timer;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class TimerTest {

    @Test
    public void test() throws Exception {
        assertThat("hello world", is(containsString("ell")));
    }
}

No comments: