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 @   xjw12345  阅读(99)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示