Java反射

一个类在内存中只有一个 Class 对象

一个类被加载后,类的整个结构都会被封装在 Class 对象中

一、反射概述:

 

 

 二、反射对象

 

 

 

 

 

列子:

package com.alipay.sofa.web.test.base.reflect;

//反射获得实体类信息
public class RefTarget {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c1 = Class.forName("com.alipay.sofa.web.test.base.reflect.EntityTest");
        System.out.println(c1);

        Class c2 = Class.forName("com.alipay.sofa.web.test.base.reflect.EntityTest");
        Class c3 = Class.forName("com.alipay.sofa.web.test.base.reflect.EntityTest");

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

    }
}

//实体类
class EntityTest{
    private String name;
    private int age;

    public EntityTest(){}

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

@Override
public String toString() {
return "EntityTest{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

 

//获取父类
Class c5 = c1.getSuperclass();

 

posted @ 2020-09-01 15:25  物联网女强人  阅读(110)  评论(0编辑  收藏  举报