Kho*_*row 2 java generics casting generic-list
我在脑海中有关于List的通用转换的内容,但老实说,我不知道是否可以实现.
我的应用程序中有这段代码片段
public String getObjectACombo() {
List<ObjectA> listA = theDAO.getObjectA();
String combo = getCombo(listA, "rootA"); // --> This line
}
public String getObjectBCombo() {
List<ObjectB> listB = theDAO.getObjectB();
String combo = getCombo(listA, "rootA"); // --> This line
}
Run Code Online (Sandbox Code Playgroud)
首先,我正在编写一些例行程序,提到" - >这一行".但是这两种方法具有完全相同的算法,可以从List <?>生成JSON字符串,该字符串已从数据库返回.所以我想用泛型方法getCombo(List <T> list,String root)替换它们.但问题是我无法做到让它发挥作用.
public <T> String getCombo(List<T> list, String root) {
Iterator<T> listItr = list.iterator();
...
while ( listItr.hasNext() ) {
jsonObj.put(list.get(i).toJson()); // --> The Error line
}
}
Run Code Online (Sandbox Code Playgroud)
错误发生在"错误行"中.ObjectA.java和ObjectB.java都包含toJson()方法,但是"方法toJson()未定义为上述行的类型T".
我尝试用(T)和Class.forName()来强制转换它,但是它们都没有用.
有没有解决这个问题的工作?它甚至可能吗?
使用定义toJson()方法的接口,例如Jsonable:) - 然后限制T:
public <T extends Jsonable> String getCombo(List<T> list, String root) {
...
}
Run Code Online (Sandbox Code Playgroud)
这样编译器知道每个T必须继承Jsonable并因此具有该toJson()方法.
编辑:这是我的意思的一个例子,使用现有的Comparable<T>界面:
public <T extends Comparable<T>> boolean compare(List<T> list, T other) {
for( T object : list ) {
if( object.compareTo( other ) == 0 ) {
return true;
}
}
return false;
}
compare( new ArrayList<String>(), "foo"); //compiles, since String implements Comparable<String>
compare( new ArrayList<Object>(), null); //doesn't compile, since Object doesn't implement Comparable<Object>
Run Code Online (Sandbox Code Playgroud)