首页 > 解决方案 > 制作一个能够识别参数类型并相应调用其常用方法的方法

问题描述

下面是三个方法的示例,它们具有几乎相同的指导者,不包括第一个(Tile、Primitive、Cube)。

假设对于这些对象,这些方法也存在:

Tile.set(int a, int b, int c){ ... }
Primitive.set(int a, int b, int c){ ... }
Cube.set(int a, int b, int c){ ... } 

现在这里有 3 种使用上述方法的不同方法:

void first(Tile tile, int a, int b, int c){
    tile.set(a,b,c);
}

void second(Primitive tile, int a, int b, int c){
    tile.set(a,b,c);
}

void third(Cube tile, int a, int b, int c){
    tile.set(a,b,c);
}

我的问题是,如果我们假设它们都具有方法.set,是否可以创建类似怪物方法的东西来识别tile(我的输入)是Tile、Primitive还是Cube

像这样的东西:

void monster(Anything tile, int a, int b, int c){
    tile.set(a,b,c);
}

//对于洛洛//

虽然我知道这是错误的,因为该方法有 3 个同名指导员,所以它应该只从 3 个中选择 1 个,无论 tile 是什么:

void monster(Tile tile, Primitive tile, Cube tile, int a, int b, int c){
    tile.set(a,b,c);
}

标签: javamethodsconstructor

解决方案


是的,您可以通过使用接口来使用策略模式。您可以通过以下方式识别它instanceof

if (dog instanceof Dog) System.out.println("dog is an instanceof Dog");

为了更具体地解决您的问题,例如:

public interface ISet {

    void set(int a, int b, int c);

}

public class Cube implements ISet {
    @Override
    public void set(int a, int b, int c) {

    }
}

public class Primitive implements ISet {
    @Override
    public void set(int a, int b, int c) {

    }
}


public class Tile implements ISet {
    @Override
    public void set(int a, int b, int c) {

    }
}

public static void main(String[] args) {
    ISet set = new Cube(); //just an example. it can be given
    if (set instanceof Cube) {
        System.out.println("instanceof Cube");
    }
}

public class A {
    public void set(ISet set) {
        set.set(0 ,0, 0);
    }
}

推荐阅读