Wie bekomme ich die MethodHandle
für einen Array-Konstruktor wie int[]::new
?Wie suche ich einen Array-Konstruktor MethodHandle mit MethodHandles.Lookup?
funktioniert das nicht:
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
MethodHandle mh = lookup.findConstructor(int[].class, MethodType.methodType(void.class, int.class));
System.out.println(mh);
System.out.println(mh.invoke());
}
Es ergibt dies:
Exception in thread "main" java.lang.NoSuchMethodException: no such constructor: [I.<init>(int)void/newInvokeSpecial
at java.lang.invoke.MemberName.makeAccessException(MemberName.java:871)
at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:990)
at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1382)
at java.lang.invoke.MethodHandles$Lookup.findConstructor(MethodHandles.java:920)
at xx.main(xx.java:11)
Caused by: java.lang.NoSuchMethodError: java.lang.Object.<init>(I)V
at java.lang.invoke.MethodHandleNatives.resolve(Native Method)
at java.lang.invoke.MemberName$Factory.resolve(MemberName.java:962)
at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:987)
... 3 more
auch nicht dies:
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
MethodHandle mh = lookup.findConstructor(int[].class, MethodType.methodType(void.class));
System.out.println(mh);
System.out.println(mh.invoke());
}
Es den Konstruktor für Object
statt zu finden scheint:
MethodHandle()Object
[email protected]
geprüft Nur, dass 'int [] :: neu 'generiert in bytecode eine synthetische Methode wie' Objekt Lambda $ MR $ neu $ neu $ 4ffde7b3 $ 1 (int len) {return new int [len]; } '. –
Im Zusammenhang mit der Frage wollen Sie sicher eine '.bindTo (int.class) .asType (MethodType.methodType (int []. Class, int.class))' ketten, um das gewünschte Handle zu erhalten, das ein 'int darstellt [] :: new' logic, dh Sie können es verwenden wie 'int [] array = (int []) mh.invokeExact (42);' dann – Holger
Danke an alle. Das funktionierte für mich: 'MethodHandles.insertArguments (lookup.findStatic (Array.class," newInstance ", MethodType.methodType (Object.class, Class.class, int.class)), 0, int.class)' – Archie