简体   繁体   English

通过功能接口方法签名获取 class 构造函数

[英]Get class constructor by functional interface method signature

I know i can use constructor reference as hihger-order method's argument like this:我知道我可以使用构造函数引用作为高阶方法的参数,如下所示:

collection.stream().map(MyClass::new);

But I have MyClass as a variable Class<MyClass> clazz = MyClass.class .但是我将MyClass作为变量Class<MyClass> clazz = MyClass.class Can I use it to pass constructor reference to .map(Function) method?我可以使用它将构造函数引用传递给.map(Function)方法吗? I want to do something like this, is there a way to do it?我想做这样的事情,有办法吗?

Class<MyClass> clazz = MyClass.class;
collection.stream().map(clazz.getConstructor())

Standard disclaimer: Use of reflection is almost always a bad idea.标准免责声明:使用反射几乎总是一个坏主意。

It is much better to go for a standard Abstract Factory or similar.对于标准抽象工厂或类似的,go 要好得多。

However, MethodHandle will construct the required Function objct with minimal overhead (I think).但是, MethodHandle将以最小的开销(我认为)构造所需的Function If you do the lookup of fn every time, there is overhead in that.如果您每次都查找fn ,那么就会产生开销。

    Function<T, R> fn = (Function<T, R>)
        MethodHandleProxies.asInterfaceInstance(
            Function.class,
            MethodHandles.lookup().findConstructor(clazz,
               MethodType.methodType(Void.TYPE, tClass)
           )
        );

Exception handling elided.省略了异常处理。

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

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