How to build a differentiable for a Generic class?

2

How would you build a differentiated constructor for classes that span a generic class?

For example, for the situation below, I would like to create a Generic constructor that could accomplish the entity = E.class; statement, but for now I could not. So that it could be invoked in the constructor of the ItemManager class.

How could we do this?

public class Generic<E> {
    private Class<E> entity;

    public void setEntity(Class<E> entity) {
        this.entity = entity;
    }

    public Generic() {
        entity = E.class;
    }
}

class ItemManager extends Generic<Item> {
    public ItemManager() {
        super(); 
    }
}
    
asked by anonymous 11.06.2014 / 21:38

3 answers

3

The intent of your code is confusing. But if I understand you want to store the entity type and not an instance of it.

So just do your builder like this:

public abstract class Generic<E> {
    private Class<E> entityClass;

    public Generic() {
        this.entityClass = (Class<E>) 
            ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
}

Note: I changed the attribute entity to entityClass to make it clear that it is not an entity that is being stored but the type (class) of the entity .

However, if you want to receive the instance of the same entity, the code looks like this:

public abstract class Generic<E> {
    private E entity;

    public void setEntity(E entity) {
        this.entity = entity;
    }
}
    
11.06.2014 / 22:07
2

It may be simpler to use Item.class where possible, and pass it to the Generic constructor:

public class Generic<E> {
    ...
    public Generic(Class<E> entity) {
        this.entity = entity;
    }
}

class ItemManager extends Generic<Item> {
    public ItemManager() {
        super(Item.class);
    }
}
    
12.06.2014 / 04:27
0

Example:

Class Generic

public class Generic <E> {
    private Class<E> entity;

    public void setEntity(Class<E> entity) {
        this.entity = entity;
    }

    public Generic(Class<E> entity) {
        this.entity = entity;
    }
}

Class ItemManager

public class ItemManager<E> extends Generic<E> {
    public ItemManager(Class<E> entity){        
        super(entity);
    }
}

Instantiating

public static void main(String[] args) 
{
    ItemManager<Item> itemManager = new ItemManager<>(Item.class); 
    System.out.print(itemManager.getEntity());

}
    
12.06.2014 / 02:53