1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public static <T, U> BiConsumer<T, U> getSetter(Class<T> clazz, String fieldName, Class<U> fieldType) throws Throwable { MethodHandles.Lookup caller = MethodHandles.lookup(); MethodType setter = MethodType.methodType(void.class, fieldType); MethodHandle target = caller.findVirtual(clazz, computeSetterName(fieldName), setter); CallSite site = LambdaMetafactory.metafactory( caller, "accept", //interfaceMethodName MethodType.methodType(BiConsumer.class), //factoryType //interfaceMethodType,泛型一律使用Object.class MethodType.methodType(void.class, Object.class, Object.class), target, //implementation target.type() //dynamicMethodType, 泛型对应的具体类型 ); MethodHandle factory = site.getTarget(); return (BiConsumer<T, U>) factory.invokeExact(); } public static String computeSetterName(String fieldName) { return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } |
当获取的函数对象是泛型时,那么interfaceMethodType和dynamicMethodType的类型是不同的。
Posted in: java基础
Comments are closed.