简体   繁体   English

如何传递一个方法作为其他方法的参数,但使最后一个方法在其签名上具有泛型作为参数?

[英]how to pass a method as parameter of other method but making the last method have a generic as parameter on its signature?

I am very novice in generics and now I just found out this. 我是泛型的新手,现在我才发现这一点。

I have a method 我有办法

//interface
myMethod(MyOtherService service)

//implementation
@Override
public myMethod(MyOtherService service){
   service.doSomething();
}

I have to clarify that MyFunction does not extend of other Class 我必须澄清MyFunction不会扩展其他类

I want to do this 我想做这个

//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();
}

}

I did that actually and compiler doesn't complain, the problem is I cannot call it with 我确实做到了,编译器没有抱怨,问题是我不能用

I would like to use a functional interface (if any) but the problem I have is that doSomething() actually receives multiple parameters. 我想使用功能接口(如果有),但是我的问题是doSomething()实际上接收了多个参数。

myMethod(myService)

since it is expecting a Function instance. 因为它期待一个Function实例。

What Im doing wrong? 我在做什么错? any idea? 任何想法?

By my opinion you just use Object as parameter,See below code, 我认为您只是使用Object作为参数,请参见以下代码,

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 {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM