package reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import reflect.User;
public class ORMTest {
public static void main(String[] args) throws SQLException,
IllegalAccessException, InvocationTargetException, Exception {
User user = (User) getObject(
"select id as Id, name as Name, updateTime as Birthday from sys_user limit 1",
User.class);
// 这里取别名就是为了便列名加set或get就可以是JavaBean中属性的set或get方法
System.out.println(user);
System.out.println(user.getName());
}
private static String[] getColNames(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for (int i = 1; i <= count; i++) {
colNames[i - 1] = rsmd.getColumnLabel(i);
}
return colNames;
}
private static Object getObject(String sql, Class clazz) throws SQLException,
Exception, IllegalAccessException, InvocationTargetException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DbConn.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
String[] colNames = getColNames(rs);// 得到所有的列名
Object object = null;
Method[] ms = clazz.getMethods();// 得到javaBean中所有set或get方法
if (rs.next()) {
object = clazz.newInstance();
for (int i = 0; i < colNames.length; i++) {
String colName = colNames[i];
String methodName = "set" + colName;// 得到set或get方法名
for (Method m : ms) {
if (methodName.equals(m.getName())) {
m.invoke(object, rs.getObject(colName));// 调用set方法,将该列的值放到set方法当中去.
break;
}
}
}
}
rs.close();
return object;
} finally {
if (rs != null) {
rs.close();
}
DbConn.closeConn(conn);
}
}
}
java 反射demo
最新推荐文章于 2024-05-15 01:51:26 发布