通过反射机制实现一个数据库工具类

public static List show(Class tclass,String sql){
  
    	List listmap = new ArrayList();
    	DBConnection db = new DBConnection();
    	ResultSet rs = null;
    	try{
    		//获取类的描述信息
    		BeanInfo beanInfo = Introspector.getBeanInfo(tclass);
    		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    		Statement stmt = (Statement)db.conn.createStatement();
    		rs = (ResultSet) stmt.executeQuery(sql);
    		while(rs.next()){
    			T t = tclass.newInstance();//生成一个实例
    			for(PropertyDescriptor propertyDescriptor : propertyDescriptors){
    				String key = propertyDescriptor.getName();
    				if(!key.equals("class")){
    					Method writeMethod = propertyDescriptor.getWriteMethod();
    					writeMethod.invoke(t, rs.getObject(key));
    				}
    			}
    			listmap.add(t);
    		}
    		rs.close();
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		db.close();
    	}
    	return listmap;
    }

这是我利用反射机制写的工具类,传入的参数有两个,分别是已经拼接好的sql语句,以及实体类的class,实体类如下:

Inform.java

package com.qcby.bean;

public class Inform {
    private long id;
    private String title;
    private String abstra;
    private String content;

    public Inform(int id, String title, String abstra, String content) {
        this.id = id;
        this.title = title;
        this.abstra = abstra;
        this.content = content;
    }

    public Inform() {
		// TODO Auto-generated constructor stub
	}
    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getAbstra() {
        return abstra;
    }

    public String getContent() {
        return content;
    }

    public void setId(long id) {
        this.id = id;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setAbstra(String abstra) {
        this.abstra = abstra;
    }

    @Override
	public String toString() {
		return "Inform [id=" + id + ", title=" + title + ", abstra=" + abstra
				+ ", content=" + content + "]";
	}

	public void setContent(String content) {
        this.content = content;
    }
}

在实体类中一定要让域的类型和数据库完全相同,比如我的数据库中id为bigint类型,在实体类中无法用int接收,只能用long.

Main中测试,TestMain.java

import java.util.List;

import com.qcby.bean.Inform;
import com.qcby.db.mysqlUtil;


public class TestMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String sql = "select * from myblog";
		
		List list = mysqlUtil.show(Inform.class, sql);
		System.out.println(list);
	}

}

测试结果:

 

好的,测试成功,这样在调用的时候随便一个实体类都可以运用这个工具类中的show方法,简直屌的一批.

你可能感兴趣的:(Java)