简体   繁体   中英

Most concise method of writing object field values to System.out in Java

What's the most concise method of logging a large number of field values? Ex, say you have 6 fields you want to output the values of, all int types at a given line.

The most obvious solution is to do something like this:

System.out.println("renderMap() xTile: " + xTile + "  yTile: " + yTile + 
    "  maxXTile: " + maxXTile + "  maxYTile: " + maxYTile + "  xPixelOffset: " + 
    xPixelOffset + "  yPixelOffset: " + yPixelOffset);

Is there a more concise and less painful method of doing this in Java, if you're making lots of changes that consistently requires you to write debugging lines such as the above?

I accept that what I did above might just be the most concise syntax, but a confirmation (or rebuttal) of that would be nice.

I ended up doing this as a solution (a bit less than my requirements above but I'll live with it):

System.out.println(String.format("%d %d  %d %d  %d %d", xTile, yTile, 
    maxXTile, maxYTile, xPixelOffset, yPixelOffset));

Make a format string and use String.format(formatstring, object.value1, object.value2, ...) with it. This is not much less concise, but it looks MUCH neater, as instead of the variables and the string's structure being intermingled, you describe entirely the format of what you want, then entirely the values you will place in it. If you've ever used printf in C, it's very similar.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format(java.util.Locale , java.lang.String, java.lang.Object...)

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

This doesn't apply to Java (unless you can do a trick with Reflection?) but in languages like Python, where all objects secretly have hashmaps of variable names to values, you could iterate over this hashmap and automatically construct a debugging string of all its variable names and values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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