Create a joint entity class using java reflection

Use the methods in the method class in java to encapsulate, and directly add the code:

public class ModelUtils {
	
	//Need a List to place the entity class
	List<Object> list=null;
	
	
	/**
	 * Constructor, assigning
	 * @param list
	 */
	public ModelUtils(List<Object> list){
		this.list=list;
	}

	/**
	 * Get the value of the property
	 * @param fName Get the name of the property of the federated entity class
	 * @return
	 */
	public <T> T getValue(String fName){
		//Assembly method name
		String methodName="get"+fName.substring(0,1).toUpperCase()+fName.substring(1);
		//Get the entity class where the method name is located
		for(Object o:list){
			try {
				//find method
				Method method = o.getClass().getMethod(methodName);
				//Check if the method exists
				if(method!=null){
					//Because invoke returns Object type, it needs to be cast to T type
					return (T)method.invoke(o);
				}				
			} catch (Exception e) {
			}
		}
		return null;
	}

	public <T> void setValue(String fName,T value,Class<T> type){
		String methodName="set"+fName.substring(0,1).toUpperCase()+fName.substring(1);
		for(Object o:list){
			try {
				//find method
				Method method = o.getClass().getMethod(methodName,type);
				if(method!=null){
					method.invoke(o, value);
					return;
				}
			} catch (Exception e) {
			}
		}
	}
}
test class



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325592351&siteId=291194637
Recommended