【工具】使用反射为类快速生成toString方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/localhost01/article/details/78172836

使用反射为类快速生成toString方法

为所处位置类打印出相应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"));
	}

猜你喜欢

转载自blog.csdn.net/localhost01/article/details/78172836
今日推荐