简体   繁体   中英

Eclipse organize import for static

Any one know, is there any way to organize static import in Eclipse ? Like shift + ctrl + o organize import, we have any keyboard shortcut for static import

import static java.lang.Math.PI; // ==> any key board shortcut?
import java.math.BigDecimal;

EDIT

My Case:

In one of my program I require to initialize 30 fields with Math.PI , I have initialized like:

private double var1=PI;
private double var2=PI;
private double var3=PI;
// other lines skipped
private double var30=PI;

To do this, I used Notepad++ to edit multiple lines at once using Shift + Alt + navigation arrows , then inserted code in eclipse .
Now, I want to do static import for the java.lang.Math.PI field (ie. import static java.lang.Math.PI; ) with keyboard shortcut that will fix imports for these 30 fields with single key stroke in Eclipse.

With Content Assist option I have to select Add static import for Math.PI 30 times, in my case.

如果您转到Window > Preferences > Java > Editor > Content Assist > Favorites它会为您提供定义org.junit.AssertWindow > Preferences > Java > Editor > Content Assist > Favorites的选项。

Have you ever tried the option: java->editor->save actions->organize imports. It may be help.

this is a screen capture

If you have several constants the implements-a-nonabstract-interface trick might do.

public interface MathEnviron {
    static final double PI = Math.PI;
    ...
    /** @since: 1.8 */
    default double sin (double x) {
         return Math.sin(x);
    }
}

public class SomeClass implements MathEnviron {

    ... dietAfter(sin(apple*PI));
}

I just discovered that Ctrl+Shift+M (Source > Add Import) can not only be used to add missing imports. It can also help with static imports. Executed on a reference to a qualified member (read Class.member), the refactoring will add a static import for the defining class and remove the class-dot expression.

For example, if you have

import java.lang.System;
class Example {
void someMethod() {
System.currentTimeMillis();
 }
}

Place the cursor on currentTimeMillis() and press Ctrl+Shift+M . This will transform the code to

import static java.lang.System.currentTimeMillis;
class Example {
void someMethod() {
currentTimeMillis();
 }
}

This feature has probably been here for a while and is documented and was announced in a New & Noteworthy. I only just discovered it the other day and found that it highly improves working with static imports. Maybe you find it useful too

another great example with good explanation provided

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM