Class对象功能_获取Constructor以及获取Method

Class对象功能_获取Constructor

Constructor构造方法:

  创建对象:

    T newInstance(Object… initargs)

    如果使用空参数构造方法创建对象,操作可以简化:Class对象的newInstance方法

    public static void main(String[] args) throws Exception{
        //1.获取Person类的Class对象
        Class personClass = Person.class;
        /*
          Constructor<?>[] getConstructors()
     ​   Constructor<T> getConstructor(类<?>… parameterTypes)
        Constructor<T> getDeclaredConstructor(类<?>… parameterTypes)
     ​   Constructor<?>[] getDeclaredConstructors()
         */

        //Constructor<T> getConstructor(类<?>… parameterTypes)
        Constructor constructor = personClass.getConstructor(String.class, int.class);
        System.out.println(constructor);
        //创建对象
        Object person = constructor.newInstance("张三", 18);
        System.out.println(person);
        System.out.println("--------------");
        Constructor constructor1 = personClass.getConstructor();
        System.out.println(constructor1);
        //创建对象
        Object person1 = constructor1.newInstance();
        System.out.println(person1);
        //创建空参对象
        Object o = personClass.newInstance();
        System.out.println(o);
    }

运行结果:

 

 

 

 

 

 

Class对象功能_获取Method

Method:方法对象

  执行方法:Object invoke(Object obj,Object… args)

  获取方法名称:String getName

    public static void main(String[] args) throws Exception{
        //1.获取Person类的Class对象
        Class personClass = Person.class;
        /*
          Method[] getMethods()
     ​   Method getMethod(String name,类<?>…parameterTypes)
     ​   Method[] getDeclaredMethods()
     ​   Method getDeclaredMethod(String name,类<?>… parameterTypes)
         */
        //获取指定名称的方法
        Method eat_method = personClass.getMethod("eat");
        Person p = new Person();
        //执行方法
        eat_method.invoke(p);

        Method eat_method2 = personClass.getMethod("eat", String.class);
        //执行方法
        eat_method2.invoke(p,"饭");
        System.out.println("------------");
        //获取所有public修饰的方法
        Method[] methods = personClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
            String name = method.getName();
            System.out.println(name);
        }
        /**
         * 获取类名
         *     String getName()
         */
        String name = personClass.getName();
        System.out.println(name);
    }

 

  

posted @ 2022-07-22 10:32  xjw12345  阅读(104)  评论(0)    收藏  举报