反射2:获取类的方法(通过方法名调用方法),属性,声明

来源:互联网 发布:淘宝冲印照片怎么样 编辑:程序博客网 时间:2024/06/06 17:45
package cn.itcast.jdbc;import java.lang.annotation.Annotation;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import cn.itcast.domain.User;public class ReflectTest {    public static void main(String[] args) throws Exception {        Class clazz = User.class;        Object obj = create(clazz);        System.out.println(obj);        System.out.println("---------");        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().getMethods(); // 获得实例的方法,包括公有的和私有的,但是没有继承的方法,        // ms=obj.getClass().getDeclaredMethods(); //获取实例的公有方法,包括继承的方法,但是没有私有的方法        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();    }}

User.java

package cn.itcast.domain;import java.util.Date;public class User {    private int id;    private String name;    private Date birthday;    private float money;    public User() {    }    public User(String name) {        this.name = name;    }    public User(float money) {        this.money = money;    }    public void showName(){        System.out.println(this.name);    }    @Override    public String toString() {        return "id=" + this.id + " name=" + this.name + " birthday="                + this.birthday + " money=" + this.money;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    public float getMoney() {        return money;    }    public void setMoney(float money) {        this.money = money;    }}
0 0