请看下面的代码:
Method methodInfo = MyClass.class.getMethod("myMethod");
Run Code Online (Sandbox Code Playgroud)
这可行,但方法名称作为字符串传递,因此即使myMethod不存在,这也将编译.
另一方面,Java 8引入了方法引用功能.它在编译时检查.可以使用此功能获取方法信息吗?
printMethodName(MyClass::myMethod);
Run Code Online (Sandbox Code Playgroud)
完整示例:
@FunctionalInterface
private interface Action {
void invoke();
}
private static class MyClass {
public static void myMethod() {
}
}
private static void printMethodName(Action action) {
}
public static void main(String[] args) throws NoSuchMethodException {
// This works, but method name is passed as a string, so this will compile
// even if myMethod does not exist
Method methodInfo = MyClass.class.getMethod("myMethod");
// Here we pass reference to a method. It …Run Code Online (Sandbox Code Playgroud) (这很难搜索,因为结果都是关于"方法参考")
我想获得一个Methodlambda表达式的实例,以便与基于遗留反射的API一起使用.应该包含clousure,因此调用thatMethod.invoke(null, ...)应该与调用lambda具有相同的效果.
我看过MethodHandles.Lookup,但它似乎只与逆向变换有关.但我想这种bind方法可能有助于包括clousure?
编辑:
说我有lambda experssion:
Function<String, String> sayHello = name -> "Hello, " + name;
Run Code Online (Sandbox Code Playgroud)
我有一个具有API 的遗留框架(SpEL)
registerFunction(String name, Method method)
Run Code Online (Sandbox Code Playgroud)
这将调用Method没有this参数的给定(即假定方法是静态的).所以我需要得到一个Method包含lambda逻辑+ clousure数据的特殊实例.
我想使用静态方法作为setter helper来捕获异常并打印有关失败操作的调试信息.我不希望只有例外细节.我想显示正在设置的属性,以便详细帮助快速调试问题.我正在使用Java 8.
我应该如何提供或检测所设置的财产?
我希望删除示例中的"名称"字符串并获得相同的结果.
我知道我不能对提供的提供的setter方法使用反射,该方法转换为lambda表达式然后转换为BiConsumer.
我得到了这个,但需要提供属性名称.
/** setter helper method **/
private static <E, V> void set(E o, BiConsumer<E, V> setter,
Supplier<V> valueSupplier, String propertyName) {
try {
setter.accept(o, valueSupplier.get());
} catch (RuntimeException e) {
throw new RuntimeException("Failed to set the value of " + propertyName, e);
}
}
Run Code Online (Sandbox Code Playgroud)
例:
Person p = new Person();
Supplier<String> nameSupplier1 = () -> "MyName";
Supplier<String> nameSupplier2 = () -> { throw new RuntimeException(); };
set(p, Person::setName, nameSupplier1, "name");
System.out.println(p.getName()); // prints MyName …Run Code Online (Sandbox Code Playgroud) 是否可以获取java.util.function.Function的方法名称.我想每次都记录正在使用的方法的名称.下面的示例打印Lambda对象,但我还没有找到一种简单的方法来获取方法名称:
public class Example {
public static void main(String[] args) {
Example ex = new Example();
ex.callService(Integer::getInteger, "123");
}
private Integer callService(Function<String, Integer> sampleMethod, String input) {
Integer output = sampleMethod.apply(input);
System.out.println("Calling method "+ sampleMethod);
return output;
}
}
Run Code Online (Sandbox Code Playgroud)