我可以解决这个问题,但我不能理解它,所以我要求一些解释(也许还有一个更好的问题标题)。
请考虑一下:
public class TBGService {
// TBGObject is an abstract base class which is extended by model classes
public <T> T doGet(TBGObject model) throws TBGServiceException {
String uri = model.buildUrl(repository) + model.getObjectKey();
GetMethod method = new GetMethod(uri);
T returned = execute(method, credentials, model.getClass());
return returned;
}
}
:
public enum TBGTaskAttributes {
private TBGTaskAttributes(String id, String type, String label, Object... flags) {
builder = new TaskAttributeBuilder();
builder.withId(id).withLabel(label);
for (Object flag : flags) {
processFlag(flag);
}
}
public abstract String getValueFromIssue(TBGIssue issue);
public abstract void setValueInIssue(TBGIssue issue, String value);
}
当我写这段代码来定义一个enum项时:
PROJECT(TaskAttribute.PRODUCT, TaskAttribute.TYPE_SINGLE_SELECT, "Project", new OptionProvider() {
@Override
public Set<Entry<String, String>> getOptions(TaskRepository repository) {
try {
List<TBGProject> list = TBGService.get(repository)
.doGet(new TBGProjects()).getProjects();
[...]
return map.entrySet();
} catch (TBGServiceException e) { [...] }
return null;
}
}) {
@Override
public String getValueFromIssue(TBGIssue issue) {
return issue.getProjectKey();
}
@Override
public void setValueInIssue(TBGIssue issue, String value) {
issue.setProjectKey(value);
}
},
[... other items ...]
我得到编译器错误(也eclipse自动完成不工作):
The method getProjects() is undefined for the type Object
如果我将doGet方法悬停,eclipse会显示它的定义如下:
<Object> Object TBGService.doGet(TBGObject model)
在其他地方,悬停显示的签名正确为:
<TBGProjects> TBGProjects TBGService.doGet(TBGObject model)
当参数为new TBGProjects()
时。
刚刚更改:
List<TBGProject> list = TBGService.get(repository)
.doGet(new TBGProjects()).getProjects();
:
TBGProjects projects = TBGService.get(repository).doGet(new TBGProjects());
List<TBGProject> = projects.getProjects();
使它工作。但是这里发生了什么?我错过了什么?
Java根据方法的返回值来推断T
的类型。
如果你不把返回值赋给任何东西,Java不知道T
应该是什么。
要解决这个问题,您可以将参数更改为T
类型,以便Java可以从您传递的参数中推断出T
:
public <T extends TBGObject> T doGet(T model) throws TBGServiceException {