Java生成對應實體類的setter和getter程式碼
阿新 • • 發佈:2022-03-25
生成到控制檯
/** * 生成setter和getter * @param clz */ public static void setAndGet(Class clz){ Field[] declaredFields = clz.getDeclaredFields(); for (Field declaredField : declaredFields) { declaredField.setAccessible(true); //獲取屬性的型別 String typeName = declaredField.getType().getName(); typeName=typeName.substring(typeName.lastIndexOf(".")+1); //System.out.println(typeName); //return屬性名用到 String returnFieldName = declaredField.getName(); //變回get方法名字 String getFieldName = declaredField.getName(); //變回set方法名字 String setFieldName = declaredField.getName(); getFieldName= "get"+String.valueOf(getFieldName.charAt(0)).toUpperCase()+getFieldName.substring(1); setFieldName = "set"+String.valueOf(setFieldName.charAt(0)).toUpperCase()+setFieldName.substring(1); System.out.println("public " + typeName +" "+getFieldName+"() "+"{"); System.out.println(" return "+returnFieldName+";"); System.out.println("}"); System.out.println(); System.out.println("public void " + setFieldName+"() "+"{"); System.out.println(" this."+returnFieldName+" = "+returnFieldName+";"); System.out.println("}"); System.out.println(); } }