以下代码实现“为所处位置类打印出相应toString方法”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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"));
}