简体   繁体   English

在受包保护的类的ctor上调用newInstance

[英]invoking newInstance on package-protected class's ctor

I have a package-protected (default) class 我有一个受软件包保护的(默认)类

package a;    
class Foo {}

So implicitly, it'll have a package-protected constructor. 因此,隐式地,它将具有受程序包保护的构造函数。

Now if I have a reference to Constructor<Foo> fooCtor = ... ; 现在,如果我有一个对Constructor<Foo> fooCtor = ...的引用Constructor<Foo> fooCtor = ... ;

Should I not get some kind of exception if I try to invoke fooCtor.newInstance() outside of package a ? 如果我尝试在fooCtor.newInstance() package a之外调用fooCtor.newInstance() ,是否应该得到某种例外?

You can't create an instance of the class unless you change the constructor's accessibility. 除非更改构造函数的可访问性,否则无法创建该类的实例。 If your Foo class is as following: 如果您的Foo班级如下:

package org.visib.a;
class Foo {
  @Override
  public String toString() {
    return "This is a foo";
  }
}

You can try instantiating a Foo but will get an IllegalAccessException , eg, try: 您可以尝试实例化Foo但是将获得IllegalAccessException ,例如,尝试:

package org.visib.b;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class FooCreator {
  public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Class<?> clazz = Class.forName("org.visib.a.Foo");
    for (Constructor<?> c : clazz.getDeclaredConstructors()) {
      System.out.println("Found constructor: " + c);
      Object foo = c.newInstance();
      System.out.println(foo);
    }
  }
}

However, you can change the access modifier of the constructor. 但是,您可以更改构造函数的访问修饰符。 Just add the following line in the for loop: 只需在for循环中添加以下行:

c.setAccessible(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM