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