反射泛型与反射注解的应用案例

package test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;


import cn.itcast.bookstore.category.domain.Category;

import cn.itcast.jdbc.TxQueryRunner;

public class Demo2 {

	
	@Test
	public void fun1() {
		User user = new User();
		user.setUid("1001");
		user.setUsername("wen");
		user.setPassword("123");
		try {
			new UserDao().add(user);
			System.out.println("添加成功");
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void fun2() {
		try {
			new UserDao().delete("333");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void fun3() {
		User user= new UserDao().load("123");
		System.out.println(user);
	}

}

//利用配置文件寻找表名,字段名
//<bean class="cn.itcast.User", tagble="tb_user">
//	<property name="username" column="uname"/>
//</bean>
//今天使用刚学的注解替代它

class BaseDAO<T> {
	private QueryRunner qr = new TxQueryRunner();
	private Class<T> beanClass;
	
	public BaseDAO() {
//		Class clazz = this.getClass();//获取当前类(子类)
//		Type type = clazz.getGenericSuperclass();//通过子类获取传递给父类的类型
//		ParameterizedType pType = (ParameterizedType)type;//强转为参数化类型B<String,Integer>
//		Type[] types = pType.getActualTypeArguments();//{String,Integer}
//		Class c = (Class)types[0];//String
		
		//反射泛型
		beanClass = (Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		
	}
	
	/**
	 * 添加方法
	 * @param bean
	 * @throws SQLException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public void add(T bean) throws SQLException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		/*
		 * 重点:如何拼凑sql语句???
		 * String sql = "insert into 表名 values(几个?)";
		 */
	
		String tableName =beanClass.getAnnotation(Table.class).value();//反射注解获取表名
		String sql = "insert into " + tableName +" values(";
		Field[] fields =  beanClass.getDeclaredFields();//通过反射获取所有的成员变量
		for(int i = 0; i < fields.length; i++) {
			 sql += "?";
			 if (i < fields.length-1) {//最后一个问号后不加逗号
				sql += ",";
			}
		}
		sql +=")";
		//反射获取所有方法成员(返回的数组的顺序是不能保证顺序的,这个不好解决,照成插入的字段顺序乱)
		Method[] methods = beanClass.getDeclaredMethods();
		List<Object> list = new ArrayList<Object>();//暂存get出的数据
		for (Method method : methods) {
			if(method.getName().indexOf("get")!=-1){//只反射get方法
				list.add(method.invoke(bean));
			}
		}
		Object[] params = new Object[list.size()];
		for(int i=0; i < list.size(); i++){//遍历list,存到数组中
//			System.out.println(list.get(i));
			params[i] = list.get(i);
		}
		qr.update(sql, params);
		
	}
	
	public void update(T bean) {
		
	}
	
	/**
	 * 删除方法
	 * @param uuid
	 * @throws SQLException 
	 */
	public void delete(String uuid) throws SQLException {
		String tableName = beanClass.getAnnotation(Table.class).value();
		String sql = "delete from " + tableName + " where ";
		Field pkField = beanClass.getDeclaredFields()[0];
		String pk = pkField.getAnnotation(ID.class).value();
		sql += pk;
		sql += "=?";
		qr.update(sql,uuid);
		System.out.println("删除成功");
	}
	
	public T load(String uuid) throws SQLException {
		String tableName = beanClass.getAnnotation(Table.class).value();
		String sql ="select * from " + tableName + " where ";
		Field pkField = beanClass.getDeclaredFields()[0];
		String pk = pkField.getAnnotation(ID.class).value();
		sql += pk;
		sql += "=?";
		System.out.println(sql);
		return (T) qr.query(sql, new BeanHandler(beanClass), uuid);
		
	}	
	
	public List<T> findAll() {
		return null;
	}
}

/**
 * 就可以写
 * @author WenHuagang
 *
 */
class UserDao extends BaseDAO<User> {
	
	public void addUser(User user) throws IllegalArgumentException, SQLException, IllegalAccessException, InvocationTargetException {
		super.add(user);
	}
	
	public void delete(String uuid) throws SQLException {
		super.delete(uuid);
	}
	
	public User load(String uuid) {
		User user = null;
		try {
			user= super.load(uuid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
}

User.java

package test;




@Table("tt_user")
public class User {
	@ID("uid")
	private String uid;
	@Column("uname")
	private String username;
	@Column("pwd")
	private String password;
	
	
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [uid=" + uid + ", username=" + username + ", password="
				+ password + "]";
	}
	
	

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值