1

I’ve extended some of the base classes of Apache Olingo 4 (still in development) to allow for stronger typing. However, my use of generics is causing an error that I didn’t expect.

I have a type parameter E that extends FooODataEntity which in turn implements the ODataEntity interface. Since FooODataEntity is an ODataEntity (just more specific) I would expect this to compile with no issues. However, getEntities() has a compilation error as shown in the code below.

Also, I would expect to be able to specify List<E> as a return type for my override of getEntities() but then I get a compile error saying:

'getEntities()' in 'com.foo.restapi.client.olingo.FooEntitySet' clashes with 'getEntities()' in 'org.apache.olingo.commons.api.domain.v4.ODataEntitySet'; attempting to use incompatible return type

What am I missing here?

FooODataEntitySet:

package com.foo.restapi.client.olingo;

import com.foo.restapi.client.FooODataEntity;
import com.foo.restapi.client.exceptions.FooRuntimeException;

import org.apache.olingo.commons.api.domain.v4.ODataAnnotation;
import org.apache.olingo.commons.api.domain.v4.ODataEntity;
import org.apache.olingo.commons.api.domain.v4.ODataEntitySet;
import org.apache.olingo.commons.core.domain.AbstractODataEntitySet;

import java.lang.reflect.Constructor;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public class FooEntitySet<E extends FooODataEntity> 
        extends AbstractODataEntitySet implements ODataEntitySet {

    private final List<E> entities = new ArrayList<E>();

    public FooEntitySet() {
        super();
    }

    @Override
    public List<ODataEntity> getEntities() {
        // compile error  
        // Incompatible types. Found: 'java.util.List<E>', 
        // required: 'java.util.List<org.apache.olingo.commons.api.domain.v4.ODataEntity>'

        return entities;
    }
}

FooODataEntity:

package com.foo.restapi.client;

public class FooODataEntity extends AbstractODataPayload 
        implements ODataEntity, ODataSingleton {

    // code not shown
}
4

1 回答 1

1

你不能这样做是有原因的。虽然 aFooODataEntity是 a ODataEntityList<FoodODataEntity>a不是a 。List<ODataEntity>

让我们更详细地介绍一下:

说我有这门课:

public class BaconODataEntity implements ODataEntity {
    // Pretend I implement all the ODataEntity things
}

我可以将 的实例添加BaconODataEntity到 aList<BaconODataEntity>和 a List<ODataEntity>... 但不能添加到 aList<FooODataEntity>中。

因此,简单地让您将 aList<FooODataEntity>转换为 aList<ODataEntity>会破坏泛型旨在引入的类型安全性,因为我可以将 a 添加BaconODataEntity到它

那么,你如何解决它?好吧,如果您绝对需要您的 List 是 a List<E extends FooODataEntity>,请创建一个新 List 并将元素复制到其中并返回该列表。

于 2014-08-11T19:22:25.540 回答