用同一个类对不同表进行访问

使用反射

public class ReflectTest {
 public static void main(String[] args) throws Exception {
  Class clazz=User.class;
  Object obj=create(clazz);
  System.out.println(obj);
  invoke1(obj,"showName");
  System.out.println("------------------");
  field(clazz);
 }
 static Object create(Class clazz) throws Exception{
  Constructor con=clazz.getConstructor(String.class);
  Object obj=con.newInstance("test name");
  return obj;
 }
 static void invoke1(Object obj,String methodName) throws Exception{
  Method[] ms=obj.getClass().getDeclaredMethods();
  ms=obj.getClass().getMethods();
  for(Method m:ms){
//   System.out.println(m.getName());
   if(methodName.equals(m.getName())){
    m.invoke(obj, null);
   }
  }
  Method m=obj.getClass().getMethod(methodName, null);
  m.invoke(obj, null);
 }
 static void field(Class clazz) throws Exception{
  Field[] fs=clazz.getDeclaredFields();
//  fs=clazz.getFields();
  for(Field f:fs){
   System.out.println(f.getName());
  }
 }
 static void annon(Class clazz)throws Exception{
  Annotation[] as=clazz.getAnnotations();
 }
}

------------------------------------------------------------------

public class ORMTest {
 public static void main(String[] args) {
  User user = (User) getObject(
    "select id as Id,name as Name,birthday as Birthday,money as Money from user where id=1",
    User.class);
  System.out.println(user);
 }

 static Object getObject(String sql, Class clazz) {
  Connection conn = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  Object object = null;
  try {
   // 建立连接
   // conn=JdbcUtils.getConnection();
   conn = JdbcUtilsSing.getInstance().getConnection();// 使用单例
   ps = conn.prepareStatement(sql);
   rs = ps.executeQuery();
   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);// 如果设置了别名使用,没有的话Name与Label一样
   }
   object = clazz.newInstance();
   Method[] ms = object.getClass().getMethods();
   while (rs.next()) {
    for (int i = 0; i < colNames.length; i++) {
     String colName = colNames[i];
     String methodName = "set" + colName;
     for (Method m : ms) {
      if (methodName.equals(m.getName())) {
       m.invoke(object, rs.getObject(colName));
      }
     }
    }

   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   JdbcUtils.free(rs, ps, conn);
  }
  return object;
 }
}

posted @ 2011-12-18 11:09  残星  阅读(278)  评论(0编辑  收藏  举报