[英]Using multiple generics in the method signature in Java
I have a interface:我有一个界面:
public interface MyInterface<T> {
Map<Long, T> getMap();
}
and two classes that implement it.和两个实现它的类。 The first one is:第一个是:
public class MyInterfaceFileImpl implements MyInterface<File> {
private Map<Long, File> map;
public MyInterfaceFileImpl(Map<Long, File> map) {
this.map = map;
}
@Override
public Map<Long, File> getMap() {
return map;
}
}
The second one is:第二个是:
public class MyInterfaceStringImpl implements MyInterface<String> {
private Map<Long, String> map;
public MyInterfaceStringImpl(Map<Long, String> map) {
this.map = map;
}
@Override
public Map<Long, String> getMap() {
return map;
}
}
I would like to pass the interface as a parameter to a method called doSomething()
.我想将接口作为参数传递给一个名为doSomething()
的方法。
public <T extends MyInterface<S>> void doSomething(T myInterface) {
Map<Long, S> ret = doSomething.getMap();
}
In this case, S would be String
if I pass MyInterfaceStringImpl
implementation and File
if I pass MyInterfaceFileImpl
implementation在这种情况下,如果我通过 MyInterfaceStringImpl 实现,S 将是String
,如果我通过MyInterfaceStringImpl
实现, MyInterfaceFileImpl
File
I have two questions:我有两个问题:
S
in doSomething()
method.如何在doSomething()
方法中定义类型S
doSomething()
method, am I using generics correctly or I should go for another solution?看看我在doSomething()
方法中想要实现的目标,我是正确使用 generics 还是应该使用 go 来获得另一个解决方案?I believe you should add the S generic argument before T like so:我相信您应该在 T 之前添加 S 通用参数,如下所示:
public <S, T extends MyInterface<S>> void doSomething(T myInterface)
{
Map<Long, S> ret = myInterface.getMap();
}
Commenting on point 2: I don't see any problem with the usage.评论第 2 点:我认为使用没有任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.