首页 > 其他分享 >464Class对象功能概述和465Class对象功能_获取Field

464Class对象功能概述和465Class对象功能_获取Field

时间:2022-09-26 15:45:53浏览次数:55  
标签:String 465Class System Person Field 464Class println personClass out

Class对象功能概述

 public static void main(String[] args) throws Exception {
        //获取Person的Class对象
        Class personClass =Person.class;

        //Constructor<T> getConstructor(类<?>...parameterTypes)
        Constructor constructor = personClass.getConstructor(String.class, int.class);
        System.out.println(constructor);
        //创建对象
        Object person = constructor.newInstance("张三", 23);
        System.out.println(person);

        System.out.println("======================");

        Constructor constructor1 = personClass.getConstructor();
        System.out.println(constructor1);
        //创建对象
        Object o = constructor1.newInstance();
        System.out.println(o);

        
    }

Class对象功能_获取Field

 public static void main(String[] args) throws Exception {
        //获取Person的Class对象
        Class personClass =Person.class;

        //获取指定名称的方法
        Method cat = personClass.getMethod("eat");
        Person person = new Person();
        //执行方法
        cat.invoke(person);

        Method cat1 = personClass.getMethod("eat", String.class);
        //执行方法
        cat1.invoke(person,"饭");

        System.out.println("==============================");

        //获取所有public修饰的方法
        Method[] methods = personClass.getMethods();
        for (Method method : methods) {
            String name = method.getName();
            System.out.println(name);
//            method.setAccessible(true);
        }

        //获取类名
        String className = personClass.getName();
        System.out.println(className);

    }

 

标签:String,465Class,System,Person,Field,464Class,println,personClass,out
From: https://www.cnblogs.com/agzq/p/16729733.html

相关文章