开发者

Why can't I import static java.lang.System.out.println?

It seems strange that I can't import static java.lang.System.out.println, when I can import static java.lang.Math.abs. Is there some reason behind this or am I doing something really stupid that I don't see at the moment? (Using Ecli开发者_JAVA技巧pse.)


Math is a class, on which abs is a static method. System.out is a static field rather than a class. So its println method isn't actually a static method, but an instance method on a static field.


Because java.lang.System.out is a static object (a PrintStream) on which you call println.

Though in eclipse you can type sysout and then press ctrl-space to have it expanded to System.out.println();


Non-static methods cannot be imported that way.

However, you can do this:

public static void println(Object o) {
    System.out.println(o);
}

// elsewhere
println("Hello World");     // can be inlined


Peter's answer seems to be the best work around. But without arguments the use cases are a bit limited.

static<T> void println(T arg) { System.out.println(arg); }


Combine printf and println

public static void println(Object format, Object... args) {
    System.out.printf(format.toString(), args);
    System.out.println();
}

@Test
public void testPrintln(){
    println(100);
    println("abc");
    println(new Date());
    println("%s=%d","abc",100);
}

output

100
abc
Wed Nov 01 22:24:20 CST 2017
abc=100


Note:import static only works on a static field or a static method of a class.

You can't import static java.lang.System.out.println, because println method is not a static method of any class(out is not even a class,it is an instance of PrintStream).

You can import static java.lang.Math.abs, because abs method is a static method of Class Math.

My suggestion is that since out is a static field of System(which is a class), you can import static java.lang.System.out, and then in your code you can use out.println instead of System.out.println for short.


My solution

package example.tools;

public class ShowMe {
    /*public static void print(String arg) {
       System.out.println(arg);
    }*/
    // or better as ceving's example
    public static<T> void print(T arg) {
        System.out.println(arg);
    }
}

In another class

import static example.tools.ShowMe.*;
    public class Flower {
        Flower() {
            print("Rose");
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜