Java使用const或static方法定义Generic Class param

时间:2017-12-06 13:24:18

标签: java generics

我想改进我的代码,特别是我使用Generic类的方式。 在我的项目中,我有大约30个课程,如下:

GenericEntity<T extends Serializable>{

    protected T id;
    public T getId(){ return id;};
...
}

public class A extends GenericEntity<Integer>{
    ...
}


public interface IService<T extends GenericEntity, T extends Serializable>{
...
}

public class AService extends IService<A,Integer>{
...
}

我想指定我的实体Id的类只有一次而不是GenericEntity中的一个,而像Service中那样指定一个。

public class A extends GenericEntity<getIdType()>{
    public final static Class getIdType(){
        return Integer.class;
    }
}

public class AService extends IService<A,A.getIdType()>{
...
}

我知道它没有那样的工作,但我希望有办法做到这一点。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

而不是:

class GenericEntity<T extends Serializable>{
    protected T id;
    public T getId(){ return id;};
}

// THESE ARE UNNECESSARY as far as I can tell
class A extends GenericEntity<Integer>{ }
class B extends GenericEntity<Long>{ }

// where U matches the generic type of GenericEntity<?>
interface IService<T extends GenericEntity<?>, U extends Serializable>{ }

class AService extends IService<A, Integer>{ }
class BService extends IService<B, Long>{ }

你可以这样做:

class GenericEntity<T extends Serializable> {
    protected T id;
    public T getIdFromEntity() { return id; }
}

// 'IService' can/should only know of 'id' as some type that extends 'Serializeable'
// So if something implements 'IService' then everything knows it will have
// a method with the signature 'T getGenericEntity(Serializable id);'
interface IService<T extends GenericEntity<?>> {
    public T getGenericEntity(Serializable id);
}

// 'AService' knows that 'id' will be an 'Integer'
class AService implements IService<GenericEntity<Integer>> {

    Map<Serializable, GenericEntity<Integer>> entityMap = new HashMap<>();

    void someMethod() {
        GenericEntity<Integer> entity = this.getGenericEntity(Integer.valueOf(1));
        Integer i1 = entity.getIdFromEntity();
        // ... do stuff
    }

    // even though 'AService' knows that 'id' will be an 'Integer'
    // the 'IService' interface defines this as taking a 'Serializable'
    // so it must keep that method signature.
    @Override public GenericEntity<Integer> getGenericEntity(Serializable id) {
        return entityMap.get(id);
    }
}

class BService implements IService<GenericEntity<Long>> {
    @Override public GenericEntity<Long> getGenericEntity(Serializable id) { return null; }
    // ... similar to AService ...
}

这会删除所有多余的class X extends GenericEntity<SOME_TYPE>类。

您只需要一个通用GenericEntity<T extends Serializable>和一个interface IService<T extends GenericEntity<?>>。此外,由于它们不是通用的AServiceBService知道扩展Serializeable(整数和长整数)的实际类型,因此它们不需要在泛型中传递给它们的额外信息

由于IService对于任何T extends GenericEntity<?>都是通用的,因此不应知道genericEntity.getId()的具体类型(,您可能不应该)。你也应该避免使它变得具体,因为它是Interface

id关注的IService类型为Serializable,因为IService<GenericEntity<?>>表示通配符?延伸Serializeable,因为{ {1}}要求它。