Runnable和Supplier之间的区别在于Supplier使用通用类型。
在运行时,供应商没有String get()方法,而有Object get()。但是您实现的方法返回一个String。您需要区分这两种类型。像这样:
public class metafactoryTest { public static void main(String[] args) throws Throwable { MethodHandles.Lookup caller = MethodHandles.lookup(); MethodType methodType = MethodType.methodType(Object.class); MethodType actualMethodType = MethodType.methodType(String.class); MethodType invokedType = MethodType.methodType(Supplier.class); CallSite site = Lambdametafactory.metafactory(caller,"get",invokedType,methodType,caller.findStatic(metafactoryTest.class, "print", actualMethodType),methodType); MethodHandle factory = site.getTarget(); Supplier<String> r = (Supplier<String>) factory.invoke(); System.out.println(r.get()); } private static String print() { return "hello world"; } }


