考虑weightclass 中的一个字段Animal。我希望能够创建用于操作此字段的getter和setter功能接口对象。
class Animal {
int weight;
}
Run Code Online (Sandbox Code Playgroud)
我目前的方法类似于用于方法的方法:
public static Supplier getter(Object obj, Class<?> cls, Field f) throws Exception {
boolean isstatic = Modifier.isStatic(f.getModifiers());
MethodType sSig = MethodType.methodType(f.getType());
Class<?> dCls = Supplier.class;
MethodType dSig = MethodType.methodType(Object.class);
String dMthd = "get";
MethodType dType = isstatic? MethodType.methodType(dCls) : MethodType.methodType(dCls, cls);
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle fctry = LambdaMetafactory.metafactory(lookup, dMthd, dType, dSig, lookup.unreflectGetter(f), sSig).getTarget();
fctry = !isstatic && obj!=null? fctry.bindTo(obj) : fctry;
return (Supplier)fctry.invoke(); …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过 LambdaMetafactory 动态创建 BiConsumer 类型的方法引用。我试图应用在https://www.cuba-platform.com/blog/think-twice-before-using-reflection/上找到的两种方法 - createVoidHandlerLambda 和这里Create BiConsumer as Field setter 而不反映Holger 的答案。
但是在这两种情况下我都遇到以下错误:
Exception in thread "main" java.lang.AbstractMethodError: Receiver class org.home.ref.App$$Lambda$15/0x0000000800066040 does not define or inherit an implementation of the resolved method abstract accept(Ljava/lang/Object;Ljava/lang/Object;)V of interface java.util.function.BiConsumer.
at org.home.ref.App.main(App.java:20)
Run Code Online (Sandbox Code Playgroud)
我的代码是这样的:
public class App {
public static void main(String[] args) throws Throwable {
MyClass myClass = new MyClass();
BiConsumer<MyClass, Boolean> setValid = MyClass::setValid;
setValid.accept(myClass, true);
BiConsumer<MyClass, Boolean> mappingMethodReferences = createHandlerLambda(MyClass.class);
mappingMethodReferences.accept(myClass, true);
}
@SuppressWarnings("unchecked")
public …Run Code Online (Sandbox Code Playgroud)