자바 반사 메커니즘 의 일부 용법

2389 단어
package com.msi.test;
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;
import com.msi.model.Diary; import com.msi.model.User; import com.msi.util.DbUtil;
public class ClassDataDemo {
            // f.getType().getConstructor(java.lang.String.class);
    List list = new ArrayList();

    Connection conn = new DbUtil().getCon();
    PreparedStatement pstat = conn.prepareStatement(sql);
    ResultSet rs = pstat.executeQuery();
    while (rs.next()) {
        Field[] fs = clazz.getDeclaredFields();
        Object obj = clazz.newInstance();
        for (Field f : fs) {
            String setname = "set"
                    + f.getName().substring(0, 1).toUpperCase()
                    + f.getName().substring(1);

            Method me = clazz.getMethod(setname, f.getType());
            // Constructor c =
            // f.getType().getConstructor(java.lang.String.class);
            // Object valueobj = c.newInstance(rs.getString(f.getName()));
            // me.invoke(obj, valueobj);
            // me.invoke(obj, rs.getString(f.getName()));
            Class rsclazz = ResultSet.class;
            String rsmname = "get"
                    + f.getType().getSimpleName().substring(0, 1)
                            .toUpperCase()
                    + f.getType().getSimpleName().substring(1);

            Method rsme = rsclazz.getMethod(rsmname, String.class);

            System.out.println(setname + "   rsmname=" + rsmname
                    + "  rsme.invoke  " + rsme.invoke(rs, f.getName()));

            me.invoke(obj, rsme.invoke(rs, f.getName()));

        }

        list.add(obj);
    }
    return list;
}

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    // List<User> userList = new ClassDataDemo().getAll(User.class,
    // "select * from t_user");
    // for (User u : userList) {
    // System.out.println(u);
    // }

    List<Diary> diaryList = new ClassDataDemo().getAll(Diary.class,
            "select d.diaryId, d.title,d.content,d.typeId from t_diary as d");
    for (Diary d : diaryList) {
        System.out.println(d);
    }

}

}

좋은 웹페이지 즐겨찾기