I am making an object formatter for use when debugging.
Formatted class:
package com.myname.somepackage;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// Allows a variable to be displayed when using Formatter.format
@Retention(RetentionPolicy.RUNTIME)
public @interface Formatted {
}
Formatter class:
package com.myname.somepackage;
import java.lang.reflect.Field;
public final class Formatter {
private Formatter() {}
// Returns a string containing the object's information, for debugging
// Format: ClassName[var1=somevalue, var2=somevalue]
// The object's variables must have the Formatted annotation to be displayed here
public static String format(Object object) {
String className = object.getClass().getSimpleName();
Field[] fields = object.getClass().getDeclaredFields();
String string = className + "[";
for (Field field : fields) {
field.setAccessible(true);
Formatted annotation = field.getAnnotation(Formatted.class);
if (annotation != null) {
String varName = field.getName();
try {
String value = field.get(object).toString();
string += varName + "=" + value + ", ";
} catch (IllegalAccessException e) {
e.printStackTrace();
string += varName + "=" + "{Unavailable}, ";
}
}
}
// remove last ", "
if (string.endsWith(", "))
string = string.substring(0, string.length() - 2);
string += "]";
return string;
}
}
A class for testing this:
package com.myname.somepackage.math.geom.r2;
import com.myname.somepackage.Formatted;
import com.myname.somepackage.Formatter;
public final class Point2d {
@Formatted
private final double x, y;
public Point2d(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return this.x;
}
public Point2d setX(double x) {
return new Point2d(x, this.y);
}
public double getY() {
return this.y;
}
public Point2d setY(double y) {
return new Point2d(this.x, y);
}
@Override
public String toString() {
return Formatter.format(this);
}
}
The code to test it:
Point2d point = new Point2d(4, 2);
System.out.println(point);
The console then outputs "Point2d[x=4.0, y=2.0]
".
How does my code look? I understand reflection is considered bad, but this is just my lazy way of quickly debugging. Thanks
@ToString
annotation. \$\endgroup\$