java 结合反射、泛型、注解获取泛型对象

由于自己也不是特别的理解,不能做过多的解释,因为这些是问过老师做出来的,我还没有学到这里。如果有解释错误的 指出来我改正一下。见谅~(如果学到这里了,会完善)

工具类(SQLUtil)核心代码:

package edu.nf.homeWork.utils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SQLUtil {

    /**
     * 
     * @param sql Sql查询语句
     * @param clazz 泛型class
     * @param params 参数值
     * @return 泛型对象
     * @throws RuntimeException
     */
    public static <T> T execute(String sql, Class<T> clazz, Object...params)throws RuntimeException {
        try {
            //获取连接对象
            Connection conn = DBUtil.getConnection();
            PreparedStatement ps = null;
            ResultSet rs = null;
            ps = conn.prepareStatement(sql);
            //循环遍历把参数插入数据库
            for (int i=1; i<=params.length; i++) {
                ps.setObject(i, params[i-1]);
            }
            rs = ps.executeQuery();
            //调用getBean方法
            T instance = getBean(rs, clazz);
            return instance;
        } catch (Exception e) {
            throw new RuntimeException();
        } 
    }
    /**
     * 
     * @param rs 结果集
     * @param clazz 泛型class
     * @return 返回一个泛型对象
     * @throws RuntimeException
     */
    public static <T> T getBean(ResultSet rs, Class<T> clazz) throws RuntimeException {
        try {
            //实例化对象
            Object instance = clazz.newInstance();
            //获取对象的所有属性(字段)
            Field[] fields = clazz.getDeclaredFields();
            rs.next();
            for (Field field : fields) {
                //属性对应的注解
                if(field.isAnnotationPresent(Column.class)) {
                    //获取对应的值
                    String columnName = field.getAnnotation(Column.class).value();
                    Object o = rs.getObject(columnName);
                    field.setAccessible(true);
                    field.set(instance, o);
                }
            }
            //强转泛型对象
            return (T)instance;
        } catch (Exception e) {
            throw new RuntimeException();
        } 
    }
}

用注解绑定实体类(Users):

package edu.nf.homeWork.utils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    
    String value();
}

实体类(Users):

package edu.nf.homeWork.entity;

import edu.nf.homeWork.utils.Column;

public class Users {
    //用注解绑定数据库里面的列
    @Column("useName")
    private String userName;
    @Column("passwords")
    private String password;

    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 "Users [userName=" + userName + ", password=" + password + "]";
    }
    
}

查询单个用户的信息的方法

/**
     * 查询单个用户的信息
     * @param userName
     * @param passWord
     * @return
     */
    public Users findUser(String userName,String passWord) {
        //sql查询语句
        String sql="select *from useinfo where usename=? and passwords=?";
        //调用工具类返回反省对象
        //参数:传入SQL语句    Users类    后面两个参数值
        Users users = SQLUtil.execute(sql, Users.class, userName, passWord);
        return users;
    }

main方法执行

public static void main(String[] args) {
        UserDao dao = new UserDao();
        //调用查询方法
        Users u = dao.findUser("11", "11");
        //显示账号
        System.out.println("账号:"+u.getUserName());
    }

//输出结果:
账号:11