开发者

Learning Java: How to make a short alias for System.out.println()

开发者 https://www.devze.com 2023-03-17 01:55 出处:网络
I would like to make an alias of or an extended version of System.out.println() for printing my variables of various types. How does one pass an argument with unknown type/class to a method?

I would like to make an alias of or an extended version of System.out.println() for printing my variables of various types. How does one pass an argument with unknown type/class to a method?

public static void p(VariableType... args) {
    Syst开发者_JAVA百科em.out.println(args[0]);
    // ...
}


You can use Object.

public static void p(Object... args) {
  System.out.println(args[0]);
  // ...
}


Unless you want lots of lines in the output, you could do.

public static <PrintableToString> void p(PrintableToString... args) {
    for(PrintableToString pts: args)
        System.out.print(pts);
    System.out.println();
}


How about this:

public static <T> void p(T... args)
{
    System.out.println(args[0]);
    // ...
}


Others have answered your question.

I'd just like to point out that your p method is a bad style and (probably) a bad idea:

  1. The method name p doesn't tell anyone what it does.

  2. Writing to standard output is usually a bad idea. The exception is when the application is designed to be run as a command line utility.

  3. Even if it is right to write to standard output, doing it that way is limiting your ability to reuse your code. A better approach is to make the stream a parameter; e.g.

    public void outputFoo(Foo foo, PrintStream ps) {
        ps.println("Foo's bar is " + foo.bar);
        // ...
    }
    
  4. If the p method is going to be used for trace prints, then using your p wrapper rather than System.err.println will hide the traceprints from style checkers like PMD. You might think this is a good thing, but in fact it is a bad thing, because now PMD won't remind you to remove the trace prints before you put your code into production / ship it to customers.


Simply use Object, because Object is the type of all Java variables.


Here's a very simple solution, which works for all my use cases:

public static final void print(Object x) { System.out.println(x); }
0

精彩评论

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