【发布时间】:2018-01-12 15:41:08
【问题描述】:
下面的代码给我编译带来了麻烦。
给我这个错误
Error:(20, 22) java: incompatible types: com.company.Main.Impl cannot be converted to T
我只需要那个接口在这个函数中工作,我不想对函数体做太多改动。
为什么这不起作用? 和 我怎样才能做到这一点?
package com.company;
public class Main {
class Impl implements someinterface, anotherinterface{
@Override
public Integer getInteger() {
return 0;
}
}
class BigObject{
public Impl get(){
return new Impl();
}
}
private <T extends someinterface & anotherinterface> Integer myfunc(BigObject bg){
T xy = bg.get(); // this line will not compile????
if (xy.isOK()) // from someinterface
return xy.getInteger(); // from anotherinterface
return null;
}
public static void main(String[] args) {
// write your code here
}
}
【问题讨论】:
-
为什么你首先需要泛型参数?从表面上看,
someinterface(应该写成CamelCase)只包含getInteger()这个方法。您可以将T替换为someinterface -
T是实现someinterface的something;它不一定是Impl。只需改用someinterface xy = ...。 -
这里的泛型是荒谬的。删除泛型声明并将
T xy = bg.get();替换为someinterface xy = bg.get();然后调试。 -
@user40129 然后创建一个
newinterface extends someinterface, anotherinterface并将T替换为newinterface。 -
@user40129 又是一个问题:为什么需要泛型?为什么不将
T替换为Impl?
标签: java