java - 制作一个能够识别参数类型并相应调用其常用方法的方法
问题描述
下面是三个方法的示例,它们具有几乎相同的指导者,不包括第一个(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);
}
解决方案
是的,您可以通过使用接口来使用策略模式。您可以通过以下方式识别它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);
}
}
推荐阅读
- apache-spark - How to REPLACE INTO using MERGE INTO for upsert in Delta Lake?
- python - 使用 Pytorch 的矩阵形式的洛伦兹内积
- r - tidyverse 在条件下用其他数据帧值替换 NA
- service - 服务失败,没有抛出异常
- c++ - 尝试使用分而治之来获取数组的所有子数组
- c# - 无法从 System.String 转换或转换为自定义对象或模型
- javascript - onDrop 提交带有文件的表单(不使用 Ajax)
- python - 仅获取 True 布尔值对应的索引
- svelte - 如何绑定到反应变量的来源?
- javascript - 选择器跳过 redux 存储更新