[Java基础]反射获取构造方法并使用

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java基础]反射获取构造方法并使用相关的知识,希望对你有一定的参考价值。

在这里插入图片描述

代码如下:

package ClassObjectPack;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> c = Class.forName("ClassObjectPack.Student");

        //只能拿公共构造函数
        Constructor<?>[] cons = c.getConstructors();
        for (Constructor con:cons)
        {
            System.out.println(con);
        }

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

        //拿所有的构造函数
        Constructor<?>[] cons01 = c.getDeclaredConstructors();
        for (Constructor con:cons01)
        {
            System.out.println(con);
        }

        //Constructor<T> getConstructor(类<?>... parameterTypes)
        //返回一个 Constructor对象,该对象反映 Constructor对象表示的类的指定的公共 类函数。

        //Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
        //返回一个 Constructor对象,该对象反映 Constructor对象表示的类或接口的指定 类函数。
        //参数:你要获取的构造方法的参数的个数和数据类型对应的字节码文件对象

        Constructor<?> con02 = c.getConstructor();

       // Constructor提供了一个类的单个构造函数的信息和访问。

       // T newInstance(Object... initargs)
       // 使用此 Constructor对象表示的构造函数,使用指定的初始化参数来创建和初始化构造函数的声明类的新实例。

        Object obj = con02.newInstance();

        System.out.println(obj);

//        Student s = new Student();
//        System.out.println(s);

    }
}

测试结果:

在这里插入图片描述

以上是关于[Java基础]反射获取构造方法并使用的主要内容,如果未能解决你的问题,请参考以下文章