0

我可以解决这个问题,但我无法理解,所以我要求一些解释(也许还有一个更好的问题标题)。

请考虑这一点:

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);

}

当我编写这段代码来定义一个枚举项时:

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 方法悬停,日食将其显示为如下定义:

 <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();

让它工作。但是这里发生了什么?我错过了什么?

4

1 回答 1

3

TJava根据您将方法的返回值分配给的内容来 推断类型。

如果您不将返回值分配给任何东西,Java 不知道T应该是什么。

要解决此问题,您可以将参数更改为类型,以便 Java 可以从您传递的参数T中推断:T

public <T extends TBGObject> T doGet(T model) throws TBGServiceException {
于 2013-01-21T00:00:09.240 回答