简体   繁体   English

在 Java 中打印到控制台的更简单方法?

[英]Simpler way to print to the console in Java?

When I was in high school, I used to do this hacky way of printing to the console in which I would define a method called say() that would allow me to not have to type System.out.println() every time I wanted to print something.当我在高中时,我曾经使用这种 hacky 方式打印到控制台,在控制台中我会定义一个名为 say() 的方法,这样我就不必每次都输入 System.out.println()打印一些东西。 It is a really simple method and looks like this:这是一个非常简单的方法,看起来像这样:

public static void say(Object o){

System.out.println(o);

}

The only downside I can really think of is the inability to print objects that can't be converted to strings, but that problem also occurs with System.out.println().我真正能想到的唯一缺点是无法打印无法转换为字符串的对象,但 System.out.println() 也会出现这个问题。 I also know that method calls take up space on the stack, but since this isn't a recursive method, I really don't think it can have the potential to blow up the stack.我也知道方法调用会占用堆栈空间,但由于这不是递归方法,我真的不认为它有可能炸毁堆栈。 If anyone has any insight on whether or not doing this is okay, please let me know!如果有人对这样做是否可以有任何见解,请告诉我!

Thanks!谢谢!

Every time you print an object System.out.println(obj) or add it to a string "value is "+obj the obj.toString() method will be called and you will have a user-friendly message when you overrided this method with some internal useful information.每次打印 object System.out.println(obj)或将其添加到字符串"value is "+obj时,都会调用obj.toString()方法,并且当您覆盖此方法时,您将收到一条用户友好的消息带有一些内部有用的信息。 Otherwise, you will have a message with the object package, class name, and object memory id. Otherwise, you will have a message with the object package, class name, and object memory id.

Call System.out.println(obj) is really too much to only print a value in the console, I personally like to make a static import and use out.println(obj) .调用System.out.println(obj)实在是太多了,只能在控制台打印一个值,我个人喜欢做一个 static 导入并使用out.println(obj) It is not the best option but is good enough.这不是最好的选择,但已经足够好了。

Example:例子:

 import static java.lang.System.out;

 public class PrintExample {

public static void main(String[] args) {
    MyObject obj = new MyObject(10);
    out.println(obj);
    MyObject2 obj2 = new MyObject2(10);
    out.println(obj2);
}

static class MyObject {

    final int value;

    MyObject(final int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "The value is " + value;
    }
}

static class MyObject2 {

    final int value;

    MyObject2(final int value) {
        this.value = value;
    }

}
}

Output: Output:

The value is 10
com.cflex.mp.api.log.PrintExample$MyObject2@60285225

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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