java反射

public interface QuestionDao {
    public List<Person> getALl();
}

BaseDao

public class BaseDao {
    private static final String DRIVERCLASS = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/question?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&amp;failOverReadOnly=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    Connection conn = null;
    PreparedStatement ps = null;
	//获取数据库连接方法
    public Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(DRIVERCLASS);
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

	//关闭数据库连接方法
    public void closeAll(Connection conn, Statement st, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (st != null)
                st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        this.conn = null;
        this.ps = null;
    }


    /**
     * 添删改通用的方法
     */
    public int execute(String sql, Object... params) {
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);//
            // 娣诲姞鍙傛暟
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            int num = ps.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, ps, null);
        }
        return -1;
    }

    public ResultSet executeQuery(String sql, Object... params) {
        conn = getConnection();
        ps = null;
        try {
            ps = conn.prepareStatement(sql);//
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            return ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 查询的通用方法
     */
    public <T> List<T> getAll(Class<T> clz, String sql, Object... params) {
        ResultSet rs = getRs(sql, params);
        List<T> datas = new ArrayList<>();
        ResultSetMetaData rsmd = null;// ResultSetMetaData存储了 ResultSet的MetaData
        try {
            rsmd = rs.getMetaData();//getMetaData包括了数据的字段名称、类型以及数目等表格所必须具备的信息。 
            int columnCount = rsmd.getColumnCount();//获取所有字段的数目
            System.out.println("总共有:" + columnCount);
            if (rs != null) {
                //解析
                while (rs.next()) {
                    // 使用反射
                    T t = clz.newInstance();//创建实例
	//Question question = new Question();
                    // 获取所有的set方法
                    List<Method> setMethod = EntityUtil.getAllSetMethod(clz);//获取EntityUtil类的getAllSetMethod方法返回值
                    for (int i = 0; i < setMethod.size(); i++) {//循环遍历setMethod集合
                        String methodName = setMethod.get(i).getName();//把setMethod集合的方法名赋值给methodName
                        for (int j = 0; j < columnCount; j++) {
                            String cLable = rsmd.getColumnLabel(j + 1);// 获取指定列的名称,从1开始
                            String cType = rsmd.getColumnTypeName(j + 1);// Varchar
                            if (methodName.toUpperCase().endsWith(cLable.toUpperCase())) {
//                                System.out.println(cLable + ":" + cType + ":" + setMethod.get(i).getName() + ":" + EntityUtil.getColumn(cLable, cType, rs));
                                setMethod.get(i).invoke(t, EntityUtil.getColumn(cLable, cType, rs));
                                break;
                            }
                        }
                    }
                    datas.add(t);
                }
            }
            return datas;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, ps, rs);
        }
        return null;
    }

    public ResultSet getRs(String sql, Object... params) {
        conn = getConnection();
        ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            // 添加参数
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            rs = ps.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
public class QuestionDaoImpl extends BaseDao implements QuestionDao {
    public List<Person> getALl() {
        System.out.println("dao 具体实现");
        return getAll(Person.class, "SELECT age FROM  person");//传入Person类对象和sql语句,返回父类的getAll方法
    }
    public List<Person> getALl1() {
        return null;
    }
}
public class Person {
    private String name;
    private char sex;
    private int age;
    class Son {
        private String name;
        private char sex;
    }
    public Person() {
        System.out.println("无参构造器");
    }
    public Person(String name) {
        this.name = name;
    }
    private Person(String name, char sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public char getSex() {
        return sex;
    }
    public void setSex(char sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", age=" + age +
                '}';
    }
}
public class Question {
    private int questionId;
    private String question;
    private String optionA;
    private String optionB;
    private String optionC;
    private String optionD;
    private int subject;
    private String answer;
    public int getQuestionId() {
        return questionId;
    }
    public void setQuestionId(int questionId) {
        this.questionId = questionId;
    }
    public String getQuestion() {
        return question;
    }
    public void setQuestion(String question) {
        this.question = question;
    }
    public String getOptionA() {
        return optionA;
    }
    public void setOptionA(String optionA) {
        this.optionA = optionA;
    }
    public String getOptionB() {
        return optionB;
    }
    public void setOptionB(String optionB) {
        this.optionB = optionB;
    }
    public String getOptionC() {
        return optionC;
    }
    public void setOptionC(String optionC) {
        this.optionC = optionC;
    }
    public String getOptionD() {
        return optionD;
    }
    public void setOptionD(String optionD) {
        this.optionD = optionD;
    }
    public int getSubject() {
        return subject;
    }
    public void setSubject(int subject) {
        this.subject = subject;
    }
    public String getAnswer() {
        return answer;
    }
    public void setAnswer(String answer) {
        this.answer = answer;
    }
    public Question(int questionId, String question, String optionA, String optionB, String optionC, String optionD,
                    int subject, String answer) {
        this.questionId = questionId;
        this.question = question;
        this.optionA = optionA;
        this.optionB = optionB;
        this.optionC = optionC;
        this.optionD = optionD;
        this.subject = subject;
        this.answer = answer;
    }
    public Question() {
        super();
    }
    @Override
    public String toString() {
        return "Question{" +
                "questionId=" + questionId +
                ", question='" + question + '\'' +
                ", optionA='" + optionA + '\'' +
                ", optionB='" + optionB + '\'' +
                ", optionC='" + optionC + '\'' +
                ", optionD='" + optionD + '\'' +
                ", subject=" + subject +
                ", answer='" + answer + '\'' +
                '}';
    }
}
public interface QuestionService {
    public List<Person> getALl();
}
public class QuestionServiceImpl implements QuestionService {
    private QuestionDao questionDao;//  完全不依赖  实现类     面向接口编程
    public QuestionServiceImpl() {
        try {
            Class clz = Class.forName("com.lyl.dao.impl.QuestionDaoImpl");
            questionDao = (QuestionDao) clz.getDeclaredConstructor().newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    @Override
    public List<Person> getALl() {
        return questionDao.getALl();
    }
}
public class EntityUtil {//定义一个EntityUtil类
    public static List<Method> getAllSetMethod(Class tClass) {	//创建一个返回值为List集合的方法getAllSetMethod
        Method[] methods = tClass.getMethods();	//返回该实例中所有public方法
        List<Method> setMethod = new ArrayList<>();	//创建List集合
        for (int i = 0; i < methods.length; i++) {	//循环遍历
            if (methods[i].getName().startsWith("set")) {	//如果方法名以set开头则为true,否则放回false
                setMethod.add(methods[i]);	//把方法添加至setMethod集合
            }
        }
        return setMethod;	//把List集合返回出去
    }

    public static void main(String[] args) {		//java程序的入口,main方法
        List<Method> sets = getAllSetMethod(Question.class);	    //获取getAllSetMethod方法的返回值,填入Question实例参数
        for (int i = 0; i < sets.size(); i++) {		//循环遍历sets集合
            System.out.println(sets.get(i));		//输出sets集合的值
        }
    }
    //创建一个返回值为Object的静态有参方法,抛出SQLException异常
    public static Object getColumn(String cLable, String cType, ResultSet rs) throws SQLException {
        switch (cType) {//switch选择cType的值
            case "VARCHAR"://判断如果cType值为VARCHAR则以String类型返回cLable参数
                return rs.getString(cLable);
            case "BIGINT":
                return rs.getLong(cLable);
            case "INTEGER":
                return rs.getInt(cLable);
            case "INT":
                return rs.getInt(cLable);
            case "TEXT":
                return rs.getString(cLable);
            case "DATETIME":
                return rs.getDate(cLable);
            case "TINYINT":
                return rs.getInt(cLable);
            case "BIT":
                return rs.getBoolean(cLable);
            case "TIMESTAMP":
                return rs.getDate(cLable);
            case "CHAR":
                return rs.getString(cLable).charAt(0);
        }
        return null;
    }
}
public class TestQuestionService {
    public static void main(String[] args) {
        QuestionService service = new QuestionServiceImpl();//获取QuestionService 类的对象
        for (int i = 0; i <service.getALl().size() ; i++) {//循环遍历service 对象的getALl方法
            System.out.println(service.getALl().get(i));//输出getALl方法的值
        }
    }
}
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        // 反射 其实是反 面向对象
        try {
            Class clz = Class.forName("com.lyl.entity.Person");
            // Constructors : 构造器
//            Constructor[] cons = clz.getConstructors();// 获取所有公开的构造器
            //Constructor[] cons = clz.getDeclaredConstructors();// 获取所有的构造器
            //通过构造器获取对象
            try {
              /*  Constructor con = clz.getDeclaredConstructor();// 获取无参构造器
                con.setAccessible(true);// 设置暴力访问
                Object obj = con.newInstance(); //  无参构造器 创建对象*/
//                System.out.println(obj);
              /*  Constructor con1 = clz.getDeclaredConstructor(java.lang.String.class);
                con1.setAccessible(true);
                Object obj = con1.newInstance("张三");*/
                Constructor con2 = clz.getDeclaredConstructor(java.lang.String.class, char.class, int.class);
                con2.setAccessible(true);
                Person obj = (Person)con2.newInstance("战三", '男', 19);
                System.out.println(obj);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
//            for (int i = 0; i < cons.length; i++) {
//                System.out.println(cons[i]);
//            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
public class Test1 {
    public static void main(String[] args) {
        // 1.获取字节码  方式一  不推荐
//        Person p= new Person();
//        Class pClz= p.getClass();
        // 2.方式二获取class对象
        Class pClz2 = Person.class;
        //3.方式三
        try {
            // 全路径  包名+类名
            Class pClz3 = Class.forName("com.lyl.entity.Person");
            System.out.println(pClz3);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
      /*  Person person = new Person();
        person.setName("张三");
        person.setAge(19);
        person.setSex('男');
        System.out.println(person);*/
    }
}
public class Test3 {
    public static void main(String[] args) {
        // 构造器
        try {
            Class clz = Class.forName("com.lyl.entity.Person");//Person类对象
            Object person = clz.newInstance();//创建实例
            //  字段
//            clz.getField("name");
            Field namef = clz.getDeclaredField("name");
            namef.setAccessible(true);
            namef.set(person, "张三");
            System.out.println(namef.get(person));
            System.out.println(person);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
public class Test4 {
    public static void main(String[] args) {
        // 构造器
        try {
            Class clz = Class.forName("com.lyl.entity.Person");
            Object obj = clz.newInstance();
            // public void setSex(char sex)
            Method method = clz.getDeclaredMethod("setSex", char.class);
            method.setAccessible(true);
            method.invoke(obj, '男');
            Method getSex = clz.getDeclaredMethod("getSex");
            char sex = (char) getSex.invoke(obj);
            System.out.println("性别是:" + sex);
            System.out.println(obj);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
public class TestClazz {
    public static void main(String[] args) {
        try {
            Class clz = Class.forName("com.lyl.dao.impl.QuestionDaoImpl");//QuestionDaoImpl对象
            System.out.println(clz.getPackage());//输出getPackage()方法
            Class[] ins = clz.getInterfaces();//创建实例
            System.out.println(ins[0]);
            Class basedao = clz.getSuperclass();
            System.out.println(basedao);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
```## 阿发## 法法师

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值