如何使用Java中的反射获取构造方法引用

时间:2022-12-30 19:03:47

I have a library that I am using in a project. It has a class which can be instantiated as

我有一个我在项目中使用的库。它有一个可以实例化的类

A object = new A(new B(value), C::new, D::new);

一个object = new A(new B(value),C :: new,D :: new);

None of the classes A, B, C, D are public, although the constructors are.

A,B,C,D类都不是公共的,尽管构造函数是。

So, I want to use Reflection to achieve this. But, I can't figure out how to do method reference C::new, D::new using reflection.

所以,我想使用Reflection实现这一目标。但是,我无法弄清楚如何使用反射方法引用C :: new,D :: new。

Would appreciate any pointers on how I can do this.

将不胜感激任何有关如何做到这一点的指示。

1 个解决方案

#1


1  

The fact that a constructor reference is used is not important. You just need to know the functional interface type into which it is converted, and then create an instance of that.

使用构造函数引用这一事实并不重要。您只需要知道转换它的功能接口类型,然后创建它的实例。

In the case of a default constructor, this would probably be Supplier<...>. You'd get something like this:

对于默认构造函数,这可能是Supplier <...>。你会得到这样的东西:

Class<C> cKlass = ...;
Constructor<C> cCons = cKlass.getDeclaredConstructor();

Supplier<C> cSupp = () -> { // similarly for class D
        try {
            return cCons.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Can not default construct " + cKlass, e);
        }
};

...

Class<A> aKlass = ...;
Constructor<A> aCons = aKlass.getDeclaredConstructor(B.class, Supplier.class, Supplier.class);
A a = aCons.newInstance(b, cSupp, dSupp);

#1


1  

The fact that a constructor reference is used is not important. You just need to know the functional interface type into which it is converted, and then create an instance of that.

使用构造函数引用这一事实并不重要。您只需要知道转换它的功能接口类型,然后创建它的实例。

In the case of a default constructor, this would probably be Supplier<...>. You'd get something like this:

对于默认构造函数,这可能是Supplier <...>。你会得到这样的东西:

Class<C> cKlass = ...;
Constructor<C> cCons = cKlass.getDeclaredConstructor();

Supplier<C> cSupp = () -> { // similarly for class D
        try {
            return cCons.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Can not default construct " + cKlass, e);
        }
};

...

Class<A> aKlass = ...;
Constructor<A> aCons = aKlass.getDeclaredConstructor(B.class, Supplier.class, Supplier.class);
A a = aCons.newInstance(b, cSupp, dSupp);