nas*_*ras 1 java methods lambda functional-programming
我正在尝试编写一个接受2个参数的方法 - 类引用和该类中方法的引用.方法本身的返回类型应该是类的方法返回类型.例如:
public <T> T myMethod (Class<?> c, <reference to a method m in class c>), where m returns something of type <T>.
Run Code Online (Sandbox Code Playgroud)
也就是说,在我的代码中,我应该能够将上述方法称为:
myMethod (SomeClass.class, x -> x.someMethod(param1, param2))
Run Code Online (Sandbox Code Playgroud)
请注意,SomeClass可以是任何类,并且someMethod可以是具有任意数量参数的该类中的任何方法.
我有理由相信在Java 8中使用lambda和功能接口是可行的,但是并不完全明白如何使用它.
功能接口方法需要使用与命名类相同类型的一个参数c,因此您需要为该类定义泛型类型,然后调用它C.
函数接口方法需要返回type的值T,但是让它重命名R以表示返回类型.
这意味着您的功能界面可以是: Function<C, R>
那么您的完整方法声明是:
public <C, R> R myMethod(Class<? extends C> clazz, Function<C, R> method)
Run Code Online (Sandbox Code Playgroud)
它可以像你展示的那样被称为.
演示
public class Test {
public static void main(String[] args) throws Exception {
Test t = new Test();
String param1 = "Foo", param2 = "Bar";
String result = t.myMethod(SomeClass.class, x -> x.someMethod(param1, param2));
System.out.println(result);
}
public <C, R> R myMethod(Class<? extends C> clazz, Function<C, R> method) throws Exception {
C obj = clazz.getConstructor().newInstance();
return method.apply(obj);
}
}
class SomeClass {
public SomeClass() {}
public String someMethod(String param1, String param2) {
return param1 + " + " + param2 + ": " + this;
}
}
Run Code Online (Sandbox Code Playgroud)
产量
Foo + Bar: test.SomeClass@5594a1b5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |