2013-05-07 109 views
0

我试图创建一个“CRUD管理器”类,执行扩展我创建的抽象超类的对象的数据库操作。抽象类是相当简单:创建一个泛型类,其类型参数仅限于某个超类

public abstract class IndexedEntity() { 

    protected Long id; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     if(id == null) 
     this.id = id; 
     else throw new UnsupportedOperationException 
     ("The ID cannot be changed once it was set."); 
    } 

} 

现在我有一对夫妇的扩展这个IndexedEntity类,这些类代表我的业务实体:CarCustomerLease

而不是创建一个CRUD经理每个业务实体,我想我会尝试创建一个支持其公共超类的通用CRUD类。

如何创建一个泛型类,在构造时需要一个类型参数,并且该类型参数仅限于某些类型 - 那些从IndexedEntity继承的类?

喜欢的东西:

public interface ICrudManager<IndexedEntity> { 

    public void add(IndexedEntity e); 

    public IndexedEntity get(long id); 

    public void update(IndexedEntity e); 

    public void delete(IndexedEntity e); 

    public List<IndexedEntity> getAll(); 

} 

是否有可能在Java中?或者,这个想法有什么不对吗?是否认为这是一个可接受的设计选择?

(我可能会放弃它的第一件事,明天,因为它可能是太难以概括了很多的行为,但此刻我很好奇它如何可以做到的。

回答

4

使用Bounded Type Parameters

public interface ICrudManager<T extends IndexedEntity> { 

    public void add(T e); 

    public IndexedEntity get(long id); 

    public void update(T e); 

    public void delete(T e); 

    public List<T> getAll(); 

} 

,你可以创建对象,如ICrudManager<Car> carManager = new CrudManagerImpl<Car>();

+0

对于泛型类和接口,在'public'之后不需要声明''。只需使用'public interface ICrudManager {'。 – rgettman 2013-05-07 17:16:49

+0

谢谢@rgettman,已编辑帖子 – sanbhat 2013-05-07 17:35:42

+1

接口中声明的方法自动为“public”。在接口中声明的变量自动为'public static final'。 – 2013-05-07 18:24:17

1
public interface MyInterface<T extends MyClass> 
1

您可以将接口线改为public <T> interface ICrudManager <T exdents IndexedEntity>这将如果您尝试插入不匹配的类,则会导致编译器错误。

如果你希望你的系统更加动态化,你可以使用一个初始化程序的抽象类来测试执行期间的类型。

public abstract <T> class { 
     { 
     if(!T instanceof IndexedEntity) 
      throw new TypeException() 
     } 
    } 
+0

您不能在泛型类型参数上使用'instanceof'。 – GriffeyDog 2013-05-07 15:14:49

相关问题