Antho
Antho

Reputation: 3

How to get subclass in a class map

Im having some trouble with classes in java, I am making a component system which uses a HashMap like so

private final Map<Class<? extends Component>, Component> components = new HashMap<>();

Component is the base type for all components, I make an abstract class called Material which is extends Component.

public abstract class Material extends Component

This forces me to extends this somewhere else to use it, for my example I make a TerrainMaterial

public class TerrainMaterial extends Material

I add a component with the following method

public <T extends Component> T addComponent(T component) {

    if (containsComponent(component.getClass())) return null;

    components.put(component.getClass(), component);
    return component;

}

In my rendering class it goes back to this HashMap to try and get the material type.

entity.getComponent(Material.class);

This internally calls this method, the containsComponent method is a comple containsKey check

public <T extends Component> T getComponent(Class<T> component) {

    if (!containsComponent(component)) return null;

    return component.cast(components.get(component));

}

The issue comes when trying to return this value, because the TerrainMaterial has a class type of TerrainMaterial and not Material it fails to find it, How can i go about making this return TerrainMaterial when using Terrain.class.

Note that i have tried adding the component like this and with casting and no change.

terrainEntity.<Material>addComponent(new TerrainMaterial(...));

Thanks in advance

Upvotes: 0

Views: 57

Answers (1)

Mathias
Mathias

Reputation: 91

Add a parameter to addComponent to pass the class:

public <T extends Component> T addComponent(Class<T> clazz, T component) {

   if (containsComponent(clazz)) return null;

   components.put(clazz, component);
   return component;
}

Upvotes: 1

Related Questions