简体   繁体   English

使用具有功能接口的构造函数通过反射实例化 class

[英]Instantiating a class via reflection using a constructor with a functional interface

If I have a class, that has a private interface inside, which has the @FunctionalInterface annotation, and a private constructor which takes an instance of a class that implements this interface, how can I construct this object using reflection with my custom implementations of the said interface?如果我有一个 class,它内部有一个私有接口,它有@FunctionalInterface注释,以及一个私有构造函数,它采用实现此接口的 class 的实例,我如何使用我的自定义实现的反射构造这个 ZA8CFDE6331BD59EB66AC96F891ZC4说界面? For instance:例如:

public class mcve {
  private mcve(mcve.wrapper<String> wrp1, mcve.wrapper<String> wrp2) {
    // ...
  }
  private mcve(mcve.wrapper<String> wrp1) {
    // ..
  }
  public static final mcve INSTANCE_1 = new mcve(ClassExtendsString::new, ClassExtendsString::new);
  public static final mcve INSTANCE_2 = new mcve(ClassExtendsString2::new, ClassExtendsString2::new);
  @FunctionalInterface
  interface wrapper<O> {
    O wrap(O object) throws Exception;
  }
}

and some code trying to accomplish what I want:和一些试图完成我想要的代码:

 Constructor<mcve> constructor;
 constructor = mcve.class.getDeclaredConstructor(??.class);
 constructor.setAccessible(true);
 mcve testInstance = constructor.newInstance(?? MyCustomClassExtendingString::new);

How do I proceed?我该如何进行? The compiler complains about Object not being a functional interface.编译器抱怨Object不是功能接口。 I'm not sure what to pass to getDeclaredConstructor and newInstance .我不确定要传递给getDeclaredConstructornewInstance什么。

Ah.啊。 You have to explicitly cast it to a wrapper :您必须将其显式转换为wrapper

mvce testInstance = constructor.newInstance((wrapper<String>) MyCustomClassExtendingString::new);

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

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