反射_Class对象功能_获取Constructor和反射_Class对象功能_获取Method

反射_Class对象功能_获取Constructor

Constructor:构造方法

>创建对象:

    T newInstance(Object...initargs)

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

public class ReflectD03 {
    public static void main(String[] args) throws Exception {
        Class per = Person.class;
        //2.获取构造方法们:
        //Constructor<T> getConstructor(类<?>...parameterTypes)
        Constructor constructor = per.getConstructor(String.class,int.class);
        System.out.println(constructor);
        //创建对象
        Object person = constructor.newInstance("张三",23);
        System.out.println(person);
        System.out.println("================");
        //使用空餐创建
        Constructor cons = per.getConstructor();
        System.out.println(cons);
        //创建对象
        Object person1 = cons.newInstance();
        System.out.println(person1);
        //简化
        Object o = per.newInstance();
        System.out.println(o);

        //Constructor<?>[] getConstructors()
        
        //Constructor<?>[] getDeclaredConstructors()

        //Constructor<T> getDeclaredConstructor(类<?>...parameterTypes)

    }
}

其余三个方法和Field同理

反射_Class对象功能_获取Method

Method:方法对象

  >执行方法:

    Object invoke(Object obj, Object...args)

  >获取方法名称

    String getName:获取方法名称

    private static void ReflectD4() throws Exception {
        /*
         3.获取成员方法们:
      >Method[] getMethods()
      >Method getMethod(String name, 类<?>... parameterTypes)

      >Method[] getMethods()
      >Method getMethod(String name, 类<?>... parameterTypes) 

         */
        Class per = Person.class;
        //Method getMethod(String name, 类<?>... parameterTypes)
        //获取指定方法名称
        Method eat_me = per.getMethod("eat");
        Person p = new Person();
        //执行方法
        eat_me.invoke(p);

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

 

 

posted @ 2022-07-22 10:31  魔光领域  阅读(23)  评论(0编辑  收藏  举报