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

后端 未结 7 1140
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 09:30

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 somet

相关标签:
7条回答
  • 2020-12-05 09:53

    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
    
    0 讨论(0)
  • 2020-12-05 10:03

    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); }
    
    0 讨论(0)
  • 2020-12-05 10:07

    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();

    0 讨论(0)
  • 2020-12-05 10:08

    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.

    0 讨论(0)
  • 2020-12-05 10:16

    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.

    0 讨论(0)
  • 2020-12-05 10:16

    Non-static methods cannot be imported that way.

    However, you can do this:

    public static void println() {
        System.out.println();
    }
    
    // elsewhere
    println();     // can be inlined
    
    0 讨论(0)
提交回复
热议问题