Java 泛型通配符用于具有多个类类型的单个参数
我有一个方法。 它接受一个参数,它可以是 Provider 或 String 类的对象。 现在,如果我告诉该方法接受 Object,那么我可以传递它 Provider
或 String
对象,但我想使用泛型使其类型安全,并且仅传递 提供者
或字符串
。我该怎么做,可能吗?
我想实现这样的目标:
public <T can be String or Provider> void myMethod(T value)
我查看了 这个问题,但它在我的情况下不起作用,因为 Provider
或 String
都不是接口。
I have a method.
It accepts a param, it can either be an object of the Provider
or String
class.
Now if I tell that method to accept Object then I can pass it Provider
or String
object, but I want to make it type safe using generics and pass only either Provider
or String
. How do I do that, is it possible?
I want to achieve something like this:
public <T can be String or Provider> void myMethod(T value)
I had a look at this question, but it would not work in my case because none of Provider
or String
is an interface.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该(也不能)为此使用泛型。相反,只需提供两个重载方法:
因为无论如何都需要有一些不同的处理,所以这种方式实际上更简单。
You should not (and can not) use generics for this. Instead simply provide two overloaded method:
Since both need to have some different handling anyway it's actually simpler this way.
不,那是不可能的。简单地使用两个重载方法怎么样?
Not, that's not possible. How about simply having two overloaded methods instead?
为什么确切地说是“Provider”或“String”?他们有什么共同点使得你的方法对他们都适用?例如,两者
可比
吗?那么你应该在其中使用Comparable
。如果他们没有共同点,也许有一个原因导致你无法做你想做的事。在这种情况下,只需使用重载,就像其他人建议的那样。Why exactly "Provider" or "String"? What do they have in common that makes your method work for both of them? For instance, are both
Comparable
? Then you should useComparable
in there. If they do not share something in common, maybe there is a reason that you cannot do what you are trying to do. In that case, just use overloading, as others suggested.