问题描述
假设我具有以下界面Foo
abstract public interface Foo {
abstract String getFoo();
}
和两个扩展Foo
,Bar1
和Bar2
public class Bar1 extends Foo{
String foo = "foobar";
public String getFoo(){
return foo;
}
}
//repeat for class Bar2
我想创建一个具有客户可以调用的方法的翻译器类,该类将扩展Foo的任何对象作为参数(例如Bar1
或Bar2
并将字符串转换为其他字符串)我做了一些挖掘,觉得仿制药将是这样做的最好方法,但是我无法正确地修改方法签名或类签名(不确定哪个,也许两个?)来允许这样做。行为。
public class TranslateBar{
//I have tried the following signatures,but clearly I'm missing something
public String translateBar(Foo<? extends Foo> pojo>{
//return translated string
}
/*
I read that Object is the supertype for all Java classes,so I thought maybe having it
take an Object in the parameters and then doing the wildcard would work,but no luck
*/
public String translateBar(Object<? extends Foo> pojo>{
//return translated string
}
在所有情况下,它都为我说了一个通俗的说法Type 'java.lang.Object'(or Foo) does not have type parameters
。它给我解决的两个选项是create a field for pojo
,它仍然不能解决<? extends Points2>
错误。
如何获取我的translateBar
方法以允许客户端传递Foo
的任何子类?
解决方法
在Java中,接受某种类型(例如Foo
)的方法也将接受Foo
的任何子类型。在这种情况下,无需使用泛型。
这是您的代码的外观:
public interface Foo {
String getFoo();
}
public class Bar1 implements Foo {
final String foo = "foobar";
@Override
public String getFoo(){
return foo;
}
}
public class TranslateBar {
public String translateBar(Foo pojo) {
//return translated string
}
}
现在,您可以使用translateBar
的任何实现(包括Foo
来调用Bar1
:
new TranslateBar().translateBar(new Bar1());
您将在不同情况下使用泛型...例如,getFoo
方法返回的类型取决于实现。
// the type T is generic and depends on the implementation
public interface Foo<T> {
T getFoo();
}
public class Bar1 implements Foo<String> {
final String foo = "foobar";
@Override
public String getFoo(){
return foo;
}
}
public class TranslateBar {
public String translateBar(Foo<?> pojo) {
//return translated string
}
}
,
在您的情况下,您不需要使用泛型,因为基本的多态性就足够了
public String translateBar(Foo pojo){
//return translated string
}
如果您只想致电getFoo()