枚举编译错误中的java匿名类

时间:2013-01-20 23:56:59

标签: java generics enums anonymous-inner-class

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

请考虑一下:

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方法悬停,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();

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

1 个答案:

答案 0 :(得分:3)

Java根据您为方法指定返回值的内容推断出T的类型。

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

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

public <T extends TBGObject> T doGet(T model) throws TBGServiceException {