类属性操作工具

      本文作为针对需要对类属性进行操作的示例,针对不同需求进行改编加工,例为对criteria自动赋值,传统通过cv大法的方式效率低下人也很累,可用此工具代劳。

package test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;


public class test {


	public static void main(String[] args) throws Exception {
		
		// 实例化需要操作的类
		TLaagent tLaagent = new TLaagent();
		try {
			testReflect(tLaagent);
		} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	public static void testReflect(Object model) throws Exception{
		String content = "";
		int i =0;
		for (Field field : model.getClass().getDeclaredFields()) {
			field.setAccessible(true);
			String name = field.getName() ;
			//将属性的首字符大写,方便构造get,set方法
			name = name.substring(0,1).toUpperCase()+name.substring(1); 
			i++;
			System.out.println("类型:"+field.getType()+"--"+name+ ":" + field.get(model) );
			if (field.getType()==String.class) {
				content+="if (StringUtil.isNotEmpty(mo.get"+name+"())) {\r\n" + 
						"            criteria.and"+name+"EqualTo(mo.get"+name+"());\r\n" + 
						"        }\r\n";
			}else {
				content+="if (mo.get"+name+"()!=null){\r\n" + 
						"            criteria.and"+name+"EqualTo(mo.get"+name+"());\r\n" + 
						"        }\r\n";
			}
			

		}
		System.out.println("属性数:"+i);
		// 写入
		try {

			File file = new File("D:\\Sim\\Project\\GetClassProperty\\mine.txt");

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();

			System.out.println("Done");

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}








 

你可能感兴趣的:(类属性操作工具)