使用反射调用构造函数会产生NoSuchMethodException

JAN*_*JAN 1 java reflection constructor

鉴于班级奖励:

public class Award {


    /*
     * 
     */

    // fields of the class 

    Award()
    {
        // some initializations


    }
Run Code Online (Sandbox Code Playgroud)

我正在尝试从Main调用此构造函数:

    try
    {
        Award myAward = Award.class.getConstructor().newInstance();
        myAward.calculateAward(); 
    }

    catch (Exception e) 
    {
       e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

但它进入异常块并产生NoSuchMethodException异常.

怎么了 ?

谢谢 !

小智 9

问题是你的构造函数不是public那么你需要使用getDeclaredConstructor().newInstance();或制作构造函数public.