栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通过反射获取类的结构小栗子

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过反射获取类的结构小栗子

 public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
        Class student = Student.class;

        //获取类的名字
        System.out.println(student.getName());//获取包名+类名
        System.out.println(student.getSimpleName());//获取类名

        System.out.println("----------------------------------");
        //值获取public属性
        for (Field field : student.getFields()) {
            System.out.println(field);
        }

        //获取所有的属性
        for (Field declaredField : student.getDeclaredFields()) {
            System.out.println(declaredField);
        }

        Field id = student.getDeclaredField("id");
        System.out.println(id);

        System.out.println("---------------------------------");
        //获得本类及其父类的所有方法
        for (Method method : student.getMethods()) {
            System.out.println("method "+method);
        }

        //获得本类的所有方法
        for (Method declaredMethod : student.getDeclaredMethods()) {
            System.out.println(declaredMethod);
        }

        System.out.println("---------------------------------");
        //获得指定方法
        Method getId = student.getMethod("getId", null);
        Method getAge = student.getMethod("getAge", null);
        Method setName = student.getMethod("setName", String.class);
        System.out.println(getId);
        System.out.println(getAge);
        System.out.println(setName);

        System.out.println("---------------------------------");
        //获得所有的构造器
        for (Constructor constructor : student.getConstructors()) {
            System.out.println(constructor);
        }

        for (Constructor declaredConstructor : student.getDeclaredConstructors()) {
            System.out.println(declaredConstructor);
        }
        //获取指定的构造器
        Constructor declaredConstructor = student.getDeclaredConstructor(Integer.class, String.class, int.class);
        System.out.println(declaredConstructor);

    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/736350.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号