以下代码实现“为所处位置类打印出相应toString方法”:
public static void main(String[] args) throws ClassNotFoundException {
// 静态方法获取当前类名
String classPath = new Object() {
public String getClassName() {
String clazzName = this.getClass().getName();
return clazzName.substring(0, clazzName.lastIndexOf('$'));
}
}.getClassName();
Class<!--?--> classType = Class.forName(classPath);
StringBuilder sb = new StringBuilder("@Override public String toString() {return \"" + classPath + " [");
for (java.lang.reflect.Field f : classType.getDeclaredFields()) {
sb.append(f.getName() + "=\"+" + f.getName() + "+\", ");
}
sb.append("]\";}");
System.out.println(sb.toString().replaceAll("^([\\s\\S]*),\\s([\\s\\S]*)", "$1$2"));
}
复制代码