初探 java反射机制

java可以通过反射机制获取类的各种信息和创建类的实例,就算将构造方法用private修饰,也可以创建,通过反射能创建很多强大的功能,算是写框架的常用方法和技巧

这里只介绍通过反射获取类的各种信息

实验类

package learn.reflect;

public class UserBean {

    private Integer id;
    private String usrname;
    private String phone;

    public UserBean(Integer id, String usrname, String phone) {
        super();
        this.id = id;
        this.usrname = usrname;
        this.phone = phone;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsrname() {
        return usrname;
    }

    public void setUsrname(String usrname) {
        this.usrname = usrname;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

}

启动类

package learn.reflect;

public class Main {

    public static void main(String[] args) {
        Class u = null;
        try {
            // 运行时加载以编译好的xxx.class文件,默认路径在classPath
            u = Class.forName("learn.reflect.UserBean");
            System.out.println("找到xxx.class文件");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 获取class后,能获取该类的一切信息进行判断或查看,有很多getxxx方法和isxxx方法
        System.out.println("class文件和包路径: " + u.getName());
        System.out.println(u.getComponentType());
        System.out.println(u.getCanonicalName());
        System.out.println(u.getModifiers());
        System.out.println(u.getSimpleName());
        System.out.println(u.getTypeName());
        System.out.println(u.getAnnotatedInterfaces());
        System.out.println(u.getAnnotatedSuperclass());
        System.out.println(u.getAnnotations());
        System.out.println(u.getConstructors());
        System.out.println(u.getDeclaredAnnotations());
        System.out.println(u.getFields());
        System.out.println(u.getMethods());
        System.out.println();


        u.getMethods();

    }

}
发布了49 篇原创文章 · 获赞 4 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章