简体   繁体   中英

Creating a generic class, with type parameter limited to a certain superclass

I'm trying to create a "CRUD manager" class, performing database operations of objects that extend an abstract superclass I created. The abstract class is fairly simple:

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.");
    }

}

Now I have a couple of classes that extend this IndexedEntity, and these classes represent my business entities: Car , Customer , Lease

Instead of creating a CRUD manager for each business entity, I figured I'd try creating a common CRUD class that supports their common superclass.

How do I create a generic class, that takes a type parameter when being constructed, and that type parameter is limited to certain types - those who inherit from IndexedEntity?

Something like:

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

}

Is it possible in Java? Or, is there anything wrong about this idea / do think it's an acceptable design choice?

(I might abandon it first thing tomorrow because it may be too difficult to generalize a lot of behavior, but at the moment I'm curious how can it be done.

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

}

and You can create objects like ICrudManager<Car> carManager = new CrudManagerImpl<Car>();

 public interface MyInterface<T extends MyClass>

You can either change the interface line to public <T> interface ICrudManager <T exdents IndexedEntity> which will result in an compiler error if you try to insert a class that doesn't match.

If you want your system to be more dynamically you can you an abstract class with an initializer that tests the type during execution.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM