1

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. 

1 Answer 1

2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

And since you have cls, it's probably worth using it to make a checked cast which will get rid of the warning (return cls.cast(ToolMap.get(cls)))
Thank you kindly. Even though C# and java are quite similar, these little minutia always get me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.