首页 > 其他 > 详细

获取类的运行时结构

时间:2020-06-29 17:46:54      阅读:68      评论:0      收藏:0      [点我收藏+]

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);
    }
}

获取类的运行时结构

原文:https://www.cnblogs.com/xd-study/p/13209144.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!