不同类型的方法参数 [英] Method argument of different types

查看:46
本文介绍了不同类型的方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写接受 a.A 或 b.B 类型参数的方法.目前已实施:

I want to write method that would accept parameter of types a.A or b.B. Currently it's implemented:

import a.A;
import b.B;

...
public void doSth(A arg) {
      SpecificClass.specificMethod(arg);
}

public void doSth(B arg) {
      SpecificClass.specificMethod(arg);
}

我想要一种通用方法doSth",它使用通配符并只接受 a.A 或 b.B.重要信息 a.A 和 b.B 不是彼此的子类型.唯一常见的类型是 java.lang.Object.

I want to have one generic method "doSth" that use wildcards and accepts only a.A or b.B. Important information a.A and b.B aren't subtypes of each other. The only common type is java.lang.Object.

有什么帮助吗?

推荐答案

假设你能做到这一点,如果 A 和 B 没有共同的超类,你将不能对参数调用任何方法,只能调用 Object 的方法.

Assuming you could do that, if A and B have no common superclass, you won't be able to call any methods on the arguments but Object's methods.

所以我认为只有两个合理的解决方案是:

So I think the only 2 reasonable solutions are:

  • 有两种方法,一种用于 A,一种用于 B(您当前的设置)
  • 有一个方法将对象作为参数,检查该参数是否是 A 或 B 的实例,如果不是则抛出 IllegalArgumentException

这篇关于不同类型的方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆