通过反射获取对象

  • Post author:
  • Post category:其他

通过反射获取对象

package other;

//什么叫反射
public class Test02 extends Object{
    public static void main(String[] args) throws ClassNotFoundException {
        //通过反射获取类的class对象
        Class c1 = Class.forName("other.User");
        System.out.println(c1);

        Class c2 = Class.forName("other.User");
        Class c3 = Class.forName("other.User");
        Class c4 = Class.forName("other.User");

        //一个类在内存中只有一个Class对象
        //一个类被加载之后,类的整个结构都会被封装在Class对象中
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
        System.out.println(c4.hashCode());
    }
}

//实体类:pojo,entity
class User{
    private String name;
    private int id;
    private int age;

    public User() {
    }

    public User(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}


版权声明:本文为king_xbstudy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。