我在泛型方面非常新手,现在我刚刚发现了这一点。
我有一个方法
//interface
myMethod(MyOtherService service)
//implementation
@Override
public myMethod(MyOtherService service){
service.doSomething();
}
我必须澄清 MyFunction 不扩展其他类
我想做这个
//interface
myMethod(GenericFunction function)
//Implementation
@Override
myMethod(GenericFunction function){
//try to cast it to MyOtherService or ServiceABC, etc
if(function instanceof(MyOtherService.class)){
//convert and call to doSomething();
}
}
我实际上这样做了,编译器没有提示,问题是我无法用
调用它我想使用函数式接口(interface)(如果有的话),但我遇到的问题是 doSomething() 实际上接收多个参数。
myMethod(myService)
因为它需要一个 Function 实例。
我做错了什么?有什么想法吗?
最佳答案
我认为你只需使用对象作为参数,请参阅下面的代码,
public class system_property implements A {
public static void main(String[] args) {
new system_property().myMethod(new MyOtherService());
}
@Override
public void myMethod(Object service) {
if (service instanceof MyOtherService) {
System.out.println("YES");
}
}
}
interface A {
void myMethod(Object service);
}
class MyOtherService {
}
关于java - 如何将一个方法作为其他方法的参数传递,但使最后一个方法在其签名上具有泛型作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52985140/