简体   繁体   English

Java:如何使用接口参数类型将变量传递给函数

[英]Java: How to pass a variable into function with interface parameter type

Assume class A implements interface B , is it possible to pass List<A> into a function with parameter List<B> : 假设类A实现接口B ,是否可以将List<A>传递给具有参数List<B>的函数:

List<A> var1;

how to call (with some fix): func(var1) 如何调用(使用一些修复): func(var1)

void func(List<B> var){
}

Any suggestion would be appreciated. 任何建议将不胜感激。 Thanks! 谢谢!

No it is not possible (at least, not without some grotesque casting). 不,这是不可能的(至少,没有一些怪诞的铸造)。 One is not the supertype of the other. 一个不是另一个的超类型。

Sure: func(Collections.<B>unmodifiableList(var1)) . 当然: func(Collections.<B>unmodifiableList(var1)) As long as you can guarantee that the list isn't being modified, that sort of call is safe. 只要您可以保证列表未被修改,那么这种呼叫是安全的。

No. List<A> is not a subtype of List<B> . 编号List<A>不是List<B>的子类型。

The reason is that if you have a List<B> , you can add objects to it whose class is any implementation of B . 原因是如果你有一个List<B> ,你可以添加对象,其类是B任何实现。 You can't do that to a List<A> . 你无法对List<A>这样做。 So there are operations that are fine for a List<B> but not a List<A> ; 因此,有一些操作适用于List<B>但不适用于List<A> ; which means that a List<A> can't possibly be a kind of List<B> . 这意味着List<A>不可能是一种List<B>

What you actually want, I think, is to use List<? extends B> 我认为你真正想要的是使用List<? extends B> List<? extends B> as the type of your parameter, instead of List<B> . List<? extends B>作为参数的类型,而不是List<B>

What a strange idea, trying to by-pass type checks. 多么奇怪的想法,试图绕过类型检查。

Do classes A and B have the same properties ? A类和B类是否具有相同的属性? If yes, consider copying them by org.apache.commons.beanutils. 如果是,请考虑通过org.apache.commons.beanutils复制它们。 BeanUtils.copyProperties (src,dest) and wrap the List argument in some conversion method. BeanUtils.copyProperties (src,dest)并在一些转换方法中包装List参数。

If you insist on passing something generally incompatible, something like this should work because of type erasure : 如果你坚持传递一些通常不兼容的东西,那么类似的东西应该因为类型擦除而起作用:

List x = var1;
func(x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM