4

Going over the documentation for this method here: getDeclaredConstructor()

I could not see any reference of it returning only public constructors.

My problem is that I have the following piece of code:

protected BaseClass internalCreate(String className) throws Exception {

    Class<? extends BaseClass> classObj = Class.forName(className)
                    .asSubclass(BaseClass.class);

    Constructor<?> ctor = classObj.getDeclaredConstructor((Class[]) null);
    ctor.setAccessible(true);

    return (BaseClass) ctor.newInstance();
}

When running this method for a class that has a default constructor visibility (package private), i am getting a MissingMethod exception. Changing the constructor to public fixes the issue.

4

1 回答 1

5

此方法返回在类中声明的构造函数,无论是否公开。但这并不意味着您可以使用返回的构造函数来实例化一个实例,这就是您收到错误的原因。如果不允许访问,则在此类构造函数上调用 setAccessible(true)。这与 getDeclaredMethod 和 getDeclaredFields 相同。

于 2013-06-07T06:47:14.657 回答