[英]Java Generics Wildcarding for a single param with multiple class types
I have a method. 我有一个方法。 It accepts a param, it can either be an object of the
Provider
or String
class. 它接受一个参数,它可以是
Provider
或String
类的对象。 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
. 现在,如果我告诉该方法接受Object,那么我可以传递它的
Provider
或String
对象,但我想使用泛型使其类型安全,并且只传递Provider
或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. 我看了一下这个问题 ,但是在我的情况下它不起作用,因为
Provider
或String
都不是一个接口。
You should not (and can not) use generics for this. 你不应该(也不能)使用泛型。 Instead simply provide two overloaded method:
而只是提供两个重载方法:
public void myMethod(String value);
// and
public void myMethod(Provider value);
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?
如何简单地使用两个重载方法呢?
public void myMethod(String value)
public void myMethod(Provider value)
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
? 例如,两者都是
Comparable
吗? Then you should use Comparable
in there. 然后你应该在那里使用
Comparable
。 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.
在这种情况下,就像其他人建议的那样使用重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.