1. 程式人生 > >java反射的一些應用,望各大神給予指正

java反射的一些應用,望各大神給予指正

第一次寫,很緊張,值得紀念的日子 2016-04-01(竟然是愚人節,我是個小白)

首先,這個是在專案裡的一個功能,因為之前專案裡都是寫死的值,每個人寫的時候都寫一堆一堆的程式碼,一堆一堆的if,else.所以就自己寫了個公共的方式,今天開始用,寫不太好,望大神們給點指導建議。

話不多說,上正文。

需求背景:

在系統中需要做使用者與統一使用者系統同步的功能,對於待更新和刪除操作的使用者,不能直接同步,需要由業務人員作業系統同步使用者和組織。最最主要的是,同步時可能不同步所有欄位,感覺這個需求停尷尬的,但是業務上需要這樣,所以默認了。

解決方案:

頁面在選中待更新專案後,彈出dialog,選擇要更新的欄位。傳到後臺,向正式表中更新選中的欄位。

公共類:

public class DesignUtils<D> {
	
	private final static String SET_HEAD = "set";
	private final static String GET_HEAD = "get";

	public D get(D newDomain,D originDomain, String ids[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		
		//建立class物件
		
		Class<? extends Object> clazzNew = newDomain.getClass();
		
		// 欄位陣列
		Field[] fields = clazzNew.getDeclaredFields();
		
		for(int i = 0; i < ids.length; i++){
    		for(int j = 0; j < fields.length; j++){
    			if(fields[j].getName().equals(ids[i])){
    				getMethod(clazzNew, SET_HEAD, fields[j]).invoke(newDomain, new Object[]{getMethod(clazzNew, GET_HEAD, fields[j]).invoke(originDomain, new Object[]{})});
    			}
    		}
		}	
		
		return newDomain;
	}

	/**
	 * 獲取實體對應的get和set方法
	 * @param clazzOrigin
	 * @param methodHead
	 * @param fieldName
	 * @return
	 */
	public Method getMethod(Class<? extends Object> clazz,String methodHead, Field field){
		if(field.getName() == null || "".equals(field.getName())){
			return null;
		}
		Method method = null;
		try {
			if(methodHead.equals(GET_HEAD)){
				method =  clazz.getMethod(getMethodName(methodHead, field.getName()), new Class[]{});
			}else if(methodHead.equals(SET_HEAD)){
				method =  clazz.getMethod(getMethodName(methodHead, field.getName()), new Class[]{field.getType()});
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return method;
	}
	
	/**
	 * 獲取get或者set方法名
	 * @param methodHead
	 * @param fieldName
	 * @return
	 */
	public String getMethodName(String methodHead, String fieldName){
		return methodHead + getFirstLetterStr(fieldName);
	}
	
	/**
	 * 將字串首字母轉換成大寫
	 * @param str
	 * @return
	 */
	public String getFirstLetterStr(String str){
		return getFirstLetter(str) + str.substring(1);
	}
	
	/**
	 * 獲取字串第一個字母,並且轉換成大寫
	 * @param str
	 * @return
	 */
	public String getFirstLetter(String str){
		return str.substring(0, 1).toUpperCase();
	}
	
	
}

user工具類(感覺可有可無):

import java.lang.reflect.InvocationTargetException;

public class UserDesign extends DesignUtils<User>{
	
	public User getNewUser(User newUser, User originUser, String[] ids) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		return get(newUser, originUser, ids);
	}
	
}

depart工具類(同上):
import java.lang.reflect.InvocationTargetException;

public class DepartDesign extends DesignUtils<Depart>{
	
	public Depart getNewDepart(Depart newDepart, Depart originDepart, String[] ids) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		return get(newDepart, originDepart, ids);
	}
}

user實體:
public class User {
	
	private String userId;
	private String userName;
	private String userAge;
	
	
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserAge() {
		return userAge;
	}
	public void setUserAge(String userAge) {
		this.userAge = userAge;
	}
}
depart實體:
public class Depart {

	private String departId;
	private String departName;
	private String departParent;
	
	public String getDepartId() {
		return departId;
	}
	public void setDepartId(String departId) {
		this.departId = departId;
	}
	public String getDepartName() {
		return departName;
	}
	public void setDepartName(String departName) {
		this.departName = departName;
	}
	public String getDepartParent() {
		return departParent;
	}
	public void setDepartParent(String departParent) {
		this.departParent = departParent;
	}
}

Test類:
import java.lang.reflect.InvocationTargetException;

public class Test extends DesignUtils<User>{

	public static void main(String[] args) {
		
		/**
		 * 使用者類  User
		 */
		
		UserDesign ud = new UserDesign();
		//DesignUtils<User> user = new DesignUtils<User>();
		
		//根據前臺選定的使用者資訊(臨時表)
		User originUser = new User();
		originUser.setUserId("1001");;
		originUser.setUserName("張三");
		originUser.setUserAge("20");
		
		//通過前臺傳遞過來(需要向更新的欄位)
		String[] idsUser = {"userName"};
		
		//需要插入正是表的實體類
		User newUser = new User();
		
		try {
			//user.get(newUser, originUser, idsUser);
			//user.getNewUser(newUser, originUser, idsUser);
			ud.get(newUser, originUser, idsUser);
			System.out.println(newUser.getUserId());
			System.out.println(newUser.getUserName());
			System.out.println(newUser.getUserAge());
			//TODO
			//對正是表進行操作
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//=============================================
		
		/**
		 * 部門Depart  與人員同理,只是方式不同
		 */
		
		//DepartDesign dd = new DepartDesign();
		DesignUtils<Depart> departUtil = new DesignUtils<Depart>();
		
		Depart originDepart = new Depart();
		originDepart.setDepartId("000201");
		originDepart.setDepartName("部門一");
		originDepart.setDepartParent("000000");
		
		Depart newDepart = new Depart();
		
		String[] idsDepart = {"departId", "departName"};
		
		try {
			//dd.getNewDepart(newDepart, originDepart, idsDepart);
			//dd.get(newDepart, originDepart, idsDepart);
			departUtil.get(newDepart, originDepart, idsDepart);
			System.out.println(newDepart.getDepartId());
			System.out.println(newDepart.getDepartName());
			System.out.println(newDepart.getDepartParent());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}