利用Class反射获取方法

来源:互联网 发布:宋神宗资治通鉴序 知乎 编辑:程序博客网 时间:2024/05/22 05:27

利用Class反射获取方法

// beanUtilspublic class BeanUtil<T> {    void setTime(T t) throws Exception {        Class bean = t.getClass();        // 获取方法的时候也需要定义好方法的参数类型        Method method = bean.getDeclaredMethod("setCreateTime", Date.class);        // 在此调用通过反射获取的方法        method.invoke(t, new Date());        System.out.println(bean.toString());    }}

// 反射结果测试public class BeanTest {    public static void main(String[] args) {        User user = new User();        BeanUtil<User> beanUtil = new BeanUtil<User>();        try {            beanUtil.setTime(user);            System.out.println(user.getCreateTime());        } catch (Exception e) {            e.printStackTrace();        }    }}
0 0
原创粉丝点击