有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何调用作为参数类型传递的不同类的方法?

我该怎么做这样的事?忽略语法错误

//some class
class A {
    //some func
    func(){
    
    }
}

class B {
    func2(){
    }
}

//Generic Class that can take type A or B
class generic<T> {
    func3(T){
        //How to do this?
        T.func();
        T.func2();
    }
}

我真的不懂泛型。如果听起来很可笑,我很抱歉


共 (2) 个答案

  1. # 1 楼答案

    所以,您非常希望有一个类,它接受另一个Util类(或它所做的任何事情),并对其调用一些标准(泛型)方法。我要做的是用这个方法创建一个接口

    public interface ExampleInterface {
       void methodToCall();
    }
    

    然后你有你的类,它实现了这个接口

    public class OtherExampleClass<T extends ExampleInterface> {
        public void call(T caller){
           caller.methodToCall();
        }
    }
    

    作为记录,到目前为止,这实际上根本不需要泛型化,我只会在类“A”和“B”具有特定的返回类型时才这样做,该返回类型是基于实例化“泛型”类时提供的返回类型

  2. # 2 楼答案

    您可以使用泛型来抽象类的“形状”,而不必关心实际的实现类

    您应该创建一个公共接口

    interface Common {
      void doWork();
    }
    
    //some class
    class A implements Common {
        void doWork() {
          func();
        }
    
        //some func
        func(){
        
        }
    }
    
    class B implements Common {
        void doWork() {
          func2();
        }
    
        func2(){
        }
    }
    
    //Generic Class that can take type A or B
    class generic<T extends Common> {
        func3(T task){
            task.doWork();
        }
    }