Domanda

I'm trying to write a curious method:

Map<Class, AbstractTool> ToolMap = new HashMap<Class, AbstractTool>();
//init'd correctly

@SuppressWarnings("unchecked")
public <T extends AbstractTool> T getTool(Class cls){
    if (ToolMap.containsKey(cls)) {
        return (T) ToolMap.get(cls);
    }
    else return null;
}

In a weird twist of events, this code actually does what I need it to do. My main issue is the fact that in order to call it, i have to make these big calls:

this.getTool<ToolType>(ToolType.class);

Not Cool.


Is there a way to write this method so that it has the following signature?:

ToolType t = this.getTool<ToolType>();

or this one

ToolType t = this.getTool(ToolType); // This one seems impossible without casting.
È stato utile?

Soluzione

The first one won't work because you're looking up a type at runtime, so that parameter is gone. The second one works fine if you just fix your method declaration. Class is a parameterized type that you declared raw.

If you do:

 Map<Class<? extends AbstractTool>, AbstractTool> ToolMap = new HashMap<Class<? extends AbstractTool>, AbstractTool>();

  @SuppressWarnings("unchecked")
  public <T extends AbstractTool> T getTool(Class<T> cls){
    if (ToolMap.containsKey(cls)) {
        return (T) ToolMap.get(cls);
    }
    else return null;
  }

Then you can do:

ToolType t = this.getTool(ToolType.class);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top