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:
The method name
p
doesn't tell anyone what it does.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.
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); // ... }
If the
p
method is going to be used for trace prints, then using yourp
wrapper rather thanSystem.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); }
精彩评论