你能从一个未知的 class 中得到构造函数吗?

Can you get constructor function from an unknown class?

嘿,所以我最近在 java 中发现了这个新东西,它允许您将静态方法或构造函数作为函数引用。如果构造函数看起来像这样

public MyClass(String str){
    System.out.println(str);
}

你可以做这样的事情 MyClass::new 然后它会 return java.util.function.Function。我想知道是否有办法从 class 的 Class 对象中获取此函数。好喜欢

Class<?> class = MyClass.class;
// VVV Like this
Function<String, MyClass> func = class::new;

或者是不可能。如果您知道如何或什至可能,请告诉我。感谢任何帮助。

使用反射,可以检索 Constructor<MyClass> 的实例,但不能直接转换为 Function<String, MyClass>

但是有方法 Constructor::newInstance 但是它会抛出几个已检查的异常。因此,需要使用支持检查异常的特殊功能接口来代替普通的 Function:

@FunctionalInterface
public interface FunctionWithExceptions<T, R, E extends Exception> {
    R apply(T t) throws E;
}

然后可以创建并使用对构造函数的 newInstance 方法的引用:

public class MyClass {
    public MyClass(String str) {
        System.out.println(str);
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        Function<String, MyClass> cons = MyClass::new;
        System.out.println(cons);
        cons.apply("Test lambda");

        Constructor<MyClass> constructor = MyClass.class.getDeclaredConstructor(String.class);

        System.out.println(constructor);
        constructor.newInstance("Test constructor");

        FunctionWithExceptions<String, MyClass, ReflectiveOperationException> funCons = constructor::newInstance;
        System.out.println(funCons);
        funCons.apply("Test reference to constructor newInstance");

    }
}

输出:

MyClass$$Lambda/0x0000000800066840@67b92f0a
Test lambda
public MyClass(java.lang.String)
Test constructor
MyClass$$Lambda/0x0000000800066c40@61f8bee4
Test reference to constructor newInstance