java 反射

来源:互联网 发布:温岭淘宝培训 编辑:程序博客网 时间:2024/04/29 21:40

利用反射获取sql语句:

重点是:1,首先通过实例对象获取他的class类,

     2,获取表单名称

     3,获取对象中的字段

     4,获取对象中的方法,最后就是拼接字符串

 示例代码:

public class Beanutil {
//初始化的时候就要传入一个实例对象obj
public static String getSelectSQL(Object obj) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, 

InvocationTargetException{
//通过实例对象获取他的class类,命名为classzz
Class<? extends Object> classzz = obj.getClass();
String tableName = classzz.getSimpleName();//获取表单名
StringBuffer sbsql = new StringBuffer();
sbsql.append("Select * from "+tableName+" ");
sbsql.append("where 1=1 ");
Field[] fields = classzz.getDeclaredFields();//获取实例对象的字段
for(Field f:fields){
String methodName = "get"+f.getName().substring(0,1).toUpperCase()+f.getName().substring(1);
Method m = classzz.getDeclaredMethod(methodName);//获取实例对象中的方法
Object o = m.invoke(obj);
if(o instanceof String){
sbsql.append(" and "+f.getName()+"=' "+o+" ' ");}else{
sbsql.append(" and "+f.getName()+" = "+o);
}
}
return sbsql.toString();
}

然后做了一个简单的测试类,传入用户姓名和用户Id

返回的是String类型的sql语句,,如下:

Select * from Userinfo where 1=1  and userId = 111 and userName=' 张三 '  and userPwd = null and useremail = null and reason = null and adress = null

0 0