use of java.lang.invoke.MethodHandles.lookup in project presto by prestodb.
the class BindableAggregationFunction method specialize.
@Override
public InternalAggregationFunction specialize(BoundVariables variables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) {
// bind variables
Signature boundSignature = applyBoundVariables(getSignature(), variables, arity);
List<Type> inputTypes = boundSignature.getArgumentTypes().stream().map(x -> typeManager.getType(x)).collect(toImmutableList());
Type outputType = typeManager.getType(boundSignature.getReturnType());
AggregationFunction aggregationAnnotation = definitionClass.getAnnotation(AggregationFunction.class);
requireNonNull(aggregationAnnotation, "aggregationAnnotation is null");
DynamicClassLoader classLoader = new DynamicClassLoader(definitionClass.getClassLoader(), getClass().getClassLoader());
AggregationMetadata metadata;
AccumulatorStateSerializer<?> stateSerializer = StateCompiler.generateStateSerializer(stateClass, classLoader);
Type intermediateType = stateSerializer.getSerializedType();
Method combineFunction = AggregationCompiler.getCombineFunction(definitionClass, stateClass);
AccumulatorStateFactory<?> stateFactory = StateCompiler.generateStateFactory(stateClass, classLoader);
try {
MethodHandle inputHandle = lookup().unreflect(inputFunction);
MethodHandle combineHandle = lookup().unreflect(combineFunction);
MethodHandle outputHandle = outputFunction == null ? null : lookup().unreflect(outputFunction);
metadata = new AggregationMetadata(generateAggregationName(getSignature().getName(), outputType.getTypeSignature(), signaturesFromTypes(inputTypes)), getParameterMetadata(inputFunction, inputTypes), inputHandle, combineHandle, outputHandle, stateClass, stateSerializer, stateFactory, outputType);
} catch (IllegalAccessException e) {
throw Throwables.propagate(e);
}
AccumulatorFactoryBinder factory = new LazyAccumulatorFactoryBinder(metadata, classLoader);
return new InternalAggregationFunction(getSignature().getName(), inputTypes, intermediateType, outputType, decomposable, factory);
}
use of java.lang.invoke.MethodHandles.lookup in project jdk8u_jdk by JetBrains.
the class T2 method main.
public static void main(String[] args) throws Throwable {
Lookup LOOKUP = T3.lookup();
Class<IllegalAccessException> IAE = IllegalAccessException.class;
assertFailure(IAE, () -> LOOKUP.findVirtual(T1.class, "m1", MethodType.methodType(void.class)));
assertFailure(IAE, () -> LOOKUP.findStatic(T1.class, "m2", MethodType.methodType(void.class)));
assertSuccess(() -> LOOKUP.findVirtual(T2.class, "m1", MethodType.methodType(void.class)));
assertSuccess(() -> LOOKUP.findVirtual(T3.class, "m1", MethodType.methodType(void.class)));
assertSuccess(() -> LOOKUP.findStatic(T2.class, "m2", MethodType.methodType(void.class)));
assertSuccess(() -> LOOKUP.findStatic(T3.class, "m2", MethodType.methodType(void.class)));
assertFailure(IAE, () -> LOOKUP.unreflect(T1.class.getDeclaredMethod("m1")));
assertFailure(IAE, () -> LOOKUP.unreflect(T1.class.getDeclaredMethod("m2")));
System.out.println("TEST PASSED");
}
use of java.lang.invoke.MethodHandles.lookup in project jdk8u_jdk by JetBrains.
the class PackageSibling method testAsInterfaceInstance0.
public void testAsInterfaceInstance0() throws Throwable {
if (CAN_SKIP_WORKING)
return;
startTest("asInterfaceInstance");
Lookup lookup = MethodHandles.lookup();
// test typical case: Runnable.run
{
countTest();
if (verbosity >= 2)
System.out.println("Runnable");
MethodType mt = MethodType.methodType(void.class);
MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "runForRunnable", mt);
Runnable proxy = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
proxy.run();
assertCalled("runForRunnable");
}
// well known single-name overloaded interface: Appendable.append
{
countTest();
if (verbosity >= 2)
System.out.println("Appendable");
ArrayList<List<?>> appendResults = new ArrayList<>();
MethodHandle append = lookup.bind(appendResults, "add", MethodType.methodType(boolean.class, Object.class));
// specialize the type
append = append.asType(MethodType.methodType(void.class, List.class));
MethodHandle asList = lookup.findStatic(Arrays.class, "asList", MethodType.methodType(List.class, Object[].class));
MethodHandle mh = MethodHandles.filterReturnValue(asList, append).asVarargsCollector(Object[].class);
Appendable proxy = MethodHandleProxies.asInterfaceInstance(Appendable.class, mh);
proxy.append("one");
proxy.append("two", 3, 4);
proxy.append('5');
assertEquals(Arrays.asList(Arrays.asList("one"), Arrays.asList("two", 3, 4), Arrays.asList('5')), appendResults);
if (verbosity >= 3)
System.out.println("appendResults=" + appendResults);
appendResults.clear();
Formatter formatter = new Formatter(proxy);
String fmt = "foo str=%s char='%c' num=%d";
Object[] fmtArgs = { "str!", 'C', 42 };
String expect = String.format(fmt, fmtArgs);
formatter.format(fmt, fmtArgs);
String actual = "";
if (verbosity >= 3)
System.out.println("appendResults=" + appendResults);
for (List<?> l : appendResults) {
Object x = l.get(0);
switch(l.size()) {
case 1:
actual += x;
continue;
case 3:
actual += ((String) x).substring((int) (Object) l.get(1), (int) (Object) l.get(2));
continue;
}
actual += l;
}
if (verbosity >= 3)
System.out.println("expect=" + expect);
if (verbosity >= 3)
System.out.println("actual=" + actual);
assertEquals(expect, actual);
}
// test case of an single name which is overloaded: Fooable.foo(...)
{
if (verbosity >= 2)
System.out.println("Fooable");
MethodHandle mh = lookup.findStatic(MethodHandlesTest.class, "fooForFooable", MethodType.methodType(Object.class, String.class, Object[].class));
Fooable proxy = MethodHandleProxies.asInterfaceInstance(Fooable.class, mh);
for (Method m : Fooable.class.getDeclaredMethods()) {
countTest();
assertSame("foo", m.getName());
if (verbosity > 3)
System.out.println("calling " + m);
MethodHandle invoker = lookup.unreflect(m);
MethodType mt = invoker.type();
Class<?>[] types = mt.parameterArray();
// placeholder
types[0] = int.class;
Object[] args = randomArgs(types);
args[0] = proxy;
if (verbosity > 3)
System.out.println("calling " + m + " on " + Arrays.asList(args));
Object result = invoker.invokeWithArguments(args);
if (verbosity > 4)
System.out.println("result = " + result);
String name = "fooForFooable/" + args[1];
Object[] argTail = Arrays.copyOfRange(args, 2, args.length);
assertCalled(name, argTail);
assertEquals(result, logEntry(name, argTail));
}
}
// test processing of thrown exceptions:
for (Throwable ex : new Throwable[] { new NullPointerException("ok"), new InternalError("ok"), new Throwable("fail"), new Exception("fail"), new MyCheckedException() }) {
MethodHandle mh = MethodHandles.throwException(void.class, Throwable.class);
mh = MethodHandles.insertArguments(mh, 0, ex);
WillThrow proxy = MethodHandleProxies.asInterfaceInstance(WillThrow.class, mh);
try {
countTest();
proxy.willThrow();
System.out.println("Failed to throw: " + ex);
assertTrue(false);
} catch (Throwable ex1) {
if (verbosity > 3) {
System.out.println("throw " + ex);
System.out.println("catch " + (ex == ex1 ? "UNWRAPPED" : ex1));
}
if (ex instanceof RuntimeException || ex instanceof Error) {
assertSame("must pass unchecked exception out without wrapping", ex, ex1);
} else if (ex instanceof MyCheckedException) {
assertSame("must pass declared exception out without wrapping", ex, ex1);
} else {
assertNotSame("must pass undeclared checked exception with wrapping", ex, ex1);
if (!(ex1 instanceof UndeclaredThrowableException) || ex1.getCause() != ex) {
ex1.printStackTrace(System.out);
}
assertSame(ex, ex1.getCause());
UndeclaredThrowableException utex = (UndeclaredThrowableException) ex1;
}
}
}
// Test error checking on bad interfaces:
for (Class<?> nonSMI : new Class<?>[] { Object.class, String.class, CharSequence.class, java.io.Serializable.class, PrivateRunnable.class, Example.class }) {
if (verbosity > 2)
System.out.println(nonSMI.getName());
try {
countTest(false);
MethodHandleProxies.asInterfaceInstance(nonSMI, varargsArray(0));
assertTrue("Failed to throw on " + nonSMI.getName(), false);
} catch (IllegalArgumentException ex) {
if (verbosity > 2)
System.out.println(nonSMI.getSimpleName() + ": " + ex);
// Object: java.lang.IllegalArgumentException:
// not a public interface: java.lang.Object
// String: java.lang.IllegalArgumentException:
// not a public interface: java.lang.String
// CharSequence: java.lang.IllegalArgumentException:
// not a single-method interface: java.lang.CharSequence
// Serializable: java.lang.IllegalArgumentException:
// not a single-method interface: java.io.Serializable
// PrivateRunnable: java.lang.IllegalArgumentException:
// not a public interface: test.java.lang.invoke.MethodHandlesTest$PrivateRunnable
// Example: java.lang.IllegalArgumentException:
// not a public interface: test.java.lang.invoke.MethodHandlesTest$Example
}
}
// Test error checking on interfaces with the wrong method type:
for (Class<?> intfc : new Class<?>[] { Runnable.class, /*arity 0*/
Fooable.class }) {
// known to be incompatible
int badArity = 1;
if (verbosity > 2)
System.out.println(intfc.getName());
try {
countTest(false);
MethodHandleProxies.asInterfaceInstance(intfc, varargsArray(badArity));
assertTrue("Failed to throw on " + intfc.getName(), false);
} catch (WrongMethodTypeException ex) {
if (verbosity > 2)
System.out.println(intfc.getSimpleName() + ": " + ex);
// Runnable: java.lang.invoke.WrongMethodTypeException:
// cannot convert MethodHandle(Object)Object[] to ()void
// Fooable: java.lang.invoke.WrongMethodTypeException:
// cannot convert MethodHandle(Object)Object[] to (Object,String)Object
}
}
}
use of java.lang.invoke.MethodHandles.lookup in project jdk8u_jdk by JetBrains.
the class PackageSibling method testUnreflectMaybeSpecial.
void testUnreflectMaybeSpecial(Class<?> specialCaller, boolean positive, Lookup lookup, Class<?> defc, Class<?> rcvc, Class<?> ret, String name, Class<?>... params) throws Throwable {
countTest(positive);
// foo/bar => foo
String methodName = name.substring(1 + name.indexOf('/'));
MethodType type = MethodType.methodType(ret, params);
Lookup specialLookup = (specialCaller != null ? maybeMoveIn(lookup, specialCaller) : null);
boolean specialAccessOK = (specialCaller != null && specialLookup.lookupClass() == specialCaller && (specialLookup.lookupModes() & Lookup.PRIVATE) != 0);
Method rmethod = defc.getDeclaredMethod(methodName, params);
MethodHandle target = null;
Exception noAccess = null;
boolean isStatic = (rcvc == null);
boolean isSpecial = (specialCaller != null);
try {
if (verbosity >= 4)
System.out.println("lookup via " + lookup + " of " + defc + " " + name + type);
if (isSpecial)
target = specialLookup.unreflectSpecial(rmethod, specialCaller);
else
target = maybeMoveIn(lookup, defc).unreflect(rmethod);
} catch (ReflectiveOperationException ex) {
noAccess = ex;
assertExceptionClass(// NSME is impossible, since it was already reflected
IllegalAccessException.class, noAccess);
if (verbosity >= 5)
ex.printStackTrace(System.out);
}
if (verbosity >= 3)
System.out.println("unreflect" + (isSpecial ? "Special" : "") + " " + defc.getName() + "." + name + "/" + type + (!isSpecial ? "" : " specialCaller=" + specialCaller) + (isStatic ? "" : " receiver=" + rcvc) + " => " + target + (noAccess == null ? "" : " !! " + noAccess));
if (positive && noAccess != null)
throw noAccess;
assertEquals(positive ? "positive test" : "negative test erroneously passed", positive, target != null);
// negative test failed as expected
if (!positive)
return;
assertEquals(isStatic, Modifier.isStatic(rmethod.getModifiers()));
Class<?>[] paramsMaybeWithSelf = params;
if (!isStatic) {
paramsMaybeWithSelf = cat(array(Class[].class, (Class) rcvc), params);
}
MethodType typeMaybeWithSelf = MethodType.methodType(ret, paramsMaybeWithSelf);
if (isStatic) {
assertEquals(typeMaybeWithSelf, target.type());
} else {
if (isSpecial)
assertEquals(specialCaller, target.type().parameterType(0));
else
assertEquals(defc, target.type().parameterType(0));
assertEquals(typeMaybeWithSelf, target.type().changeParameterType(0, rcvc));
}
Object[] argsMaybeWithSelf = randomArgs(paramsMaybeWithSelf);
printCalled(target, name, argsMaybeWithSelf);
target.invokeWithArguments(argsMaybeWithSelf);
assertCalled(name, argsMaybeWithSelf);
if (verbosity >= 1)
System.out.print(':');
}
use of java.lang.invoke.MethodHandles.lookup in project jdk8u_jdk by JetBrains.
the class PackageSibling method testRunnableProxy0.
public void testRunnableProxy0() throws Throwable {
if (CAN_SKIP_WORKING)
return;
startTest("testRunnableProxy");
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle run = lookup.findStatic(lookup.lookupClass(), "runForRunnable", MethodType.methodType(void.class));
Runnable r = MethodHandleProxies.asInterfaceInstance(Runnable.class, run);
testRunnableProxy(r);
assertCalled("runForRunnable");
}
Aggregations