java 初始化默認值

在mybatis中,如果初始化值,會導致updateSelective時,把原來的值替換掉。因此不建議使用初始化值。

但在freemark前端時,如果沒有值初始化值,需要額外增加判斷語句。這就是需要初始化值的原因。這個方法不會對已經存在的值進 行更改。對其它未初始化值不會進行更改。

public static <T> T IntialValue(T clazz) throws Exception{
		List<Method> getmethods=new ArrayList<Method>();
		Map<String,Class<?>[] > setmethods=new HashMap<String,Class<?>[] >();
		for(Class<?>  claz=clazz.getClass();claz!=Object.class;claz=claz.getClass().getSuperclass()) {
			Method[] methods = claz.getMethods();
			for (int i=0;i<methods.length;i++) {
				Method m =methods[i];
				if(m.getName().toLowerCase().startsWith("get")) {
					if(m.getParameterTypes().length==0) {
						getmethods.add(m);
					}
				}
				if(m.getName().toLowerCase().startsWith("set")) {
					setmethods.put(m.getName(), m.getParameterTypes());
				}
			}
		}
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, 1970);
		calendar.set(Calendar.MONTH, 0);
		calendar.set(Calendar.DATE, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		for(Method m:getmethods) {
			Object obj = m.invoke(clazz, null);
			if(obj==null) {
				String setstr = "set" + m.getName().substring(3);
				Method method = clazz.getClass().getMethod(setstr, setmethods.get(setstr));

				Class<?> class_param = setmethods.get(setstr)[0];

				if(class_param==String.class||class_param==char.class) {
					method.invoke(clazz, "");
				}
				if(class_param==Date.class) {
					method.invoke(clazz, new Date(calendar.getTimeInMillis()));
				}
				if(class_param==Integer.class||
						class_param==Byte.class||class_param==Short.class) {
					method.invoke(clazz, 0);
				}
				if(class_param==Long.class) {
					method.invoke(clazz, 0L);
				}
				if(class_param==Boolean.class) {
					method.invoke(clazz, false);
				}
			}
		}
		return (T)clazz;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章