建议使用下面的代码。对我来说,它看起来不错:我确实获得了一个 MethodType,它不接受参数作为输入,并生成 A 的实例。 a 的默认构造函数匹配 在我看来,这个描述,所以我希望 findConstructor(mt) 有效。但是,我遇到了异常。有什么想法,我做错了什么吗?
谢谢,
约亨
Exception in thread "main" java.lang.NoSuchMethodException: no such constructor: com.github.jochenw.afw.core.rflct.RflctDemo$A.<init>()A/newInvokeSpecial
at java.base/java.lang.invoke.MemberName.makeAccessException(MemberName.java:974)
at java.base/java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1117)
at java.base/java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:3649)
at java.base/java.lang.invoke.MethodHandles$Lookup.findConstructor(MethodHandles.java:2750)
at com.github.jochenw.afw.core.rflct.RflctDemo.main(RflctDemo.java:18)
Caused by: java.lang.NoSuchMethodError: 'com.github.jochenw.afw.core.rflct.RflctDemo$A com.github.jochenw.afw.core.rflct.RflctDemo$A.<init>()'
at java.base/java.lang.invoke.MethodHandleNatives.resolve(Native Method)
at java.base/java.lang.invoke.MemberName$Factory.resolve(MemberName.java:1085)
at java.base/java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1114)
... 3 more
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MethodHandles.Lookup;
public class RflctDemo {
/** Instance class, that has a no-args constructor.
*/
public static class A {
private boolean valid;
/** Creates a new instance with {@link #isValid() valid} == false.
*/
public A() { this(false); }
A(boolean pValid) { valid = pValid; }
boolean isValid() { return valid; }
void setValid(boolean pValid) { valid = pValid; }
}
public static void main(String[] pArgs) throws Throwable {
final Lookup lookup = MethodHandles.privateLookupIn(A.class, MethodHandles.lookup());
final MethodType mt = MethodType.methodType(A.class /* No parameters */);
final MethodHandle mh = lookup.findConstructor(A.class, mt);
final A a = (A) mh.invoke(/* No üarameters */);
}
}