Class.getDeclaredConstructor()方法用于获取指定参数类型的构造方法,包括私有构造方法。

语法: public Constructor getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException

参数:

  • parameterTypes:构造方法参数的类型

返回值: 返回一个Constructor对象,该对象表示指定参数类型的构造方法

示例:

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

public class MyClass {
    private String name;
    private int age;

    public MyClass(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        try {
            // 获取指定参数类型的构造方法
            Class<?> clazz = MyClass.class;
            Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, int.class);

            // 使用构造方法创建对象
            Object obj = constructor.newInstance("John", 25);
            MyClass myClass = (MyClass) obj;

            // 打印对象属性
            System.out.println(myClass.name);
            System.out.println(myClass.age);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

输出结果:

John
25
``
ClassgetDeclaredConstructor的使用

原文地址: https://www.cveoy.top/t/topic/hUPd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录