获取类的运行时结构

1.9、获取类的运行时结构

public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.xu.reflection.User");

        //获得类名
        User user = new User();
        c1 = user.getClass();
        System.out.println(c1.getName());//获得类的名字  包名 + 类名
        System.out.println(c1.getSimpleName());//获得类的简单名字  类名
        System.out.println("=========");

        //获得类的属性
        Field[] fields = c1.getFields();    //获得public修饰的属性
        fields = c1.getDeclaredFields();    //获得所有属性
        for (Field field : fields) {
            System.out.println(field);
        }
        //获得指定的属性值
        Field name = c1.getDeclaredField("name");
        System.out.println(name);
        //获得类的方法
        System.out.println("=====================");
        Method[] methods = c1.getMethods();//查找当前类及父类所有的public方法
        for (Method method : methods) {
            System.out.println("子类及父类公有的"+method);
        }
        methods = c1.getDeclaredMethods();//查找当前类所有的方法
        for (Method method : methods) {
            System.out.println("子类所有的"+method);
        }
        Method getName = c1.getMethod("getName", null);
        System.out.println(getName);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(setName);
        //获得构造器
        System.out.println("===========");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        constructors = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        Constructor constructor = c1.getDeclaredConstructor(int.class, String.class,int.class);
        System.out.println(constructor);
    }
}

猜你喜欢

转载自www.cnblogs.com/xd-study/p/13209144.html