Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics: Declare map value of generic type

I am new to generics.

Having a Map like

private static Map<String, Object> map;

and a method like

public <T> T getObject(final Class<T> myClass) {
    return (T)map.get(myClass);
}

How to change the map declaration in order to not have to do the cast when returning from the method ?

like image 393
Display Name Avatar asked Jun 13 '12 10:06

Display Name


People also ask

How do you initialize a generic map in Java?

Suppose if the key is of type String and the corresponding value is of type Integer, then we can initialize it as, Map< String , Integer > map = new HashMap< String ,Integer >(); The map can now only accept String instances as key and Integer instances as values.

Can you create an object of generic type?

Constructing an Instance of a Generic TypeYou cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.

How do you provide a parametrized type for a generic?

In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.

How do you declare a generic variable in Java?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.


1 Answers

You would need to make a generic class, not a generic method:

public class MyClass<T> {
   private Map<String, T> map;

   public T getObject(final String key) {
    return map.get(key);
   }
}

Also, I changed the parameter from a Class to a String. It doesn't make sense to pass a Class if map.get() expects a String.

Edit: I didn't notice that map was static. If you can change it to non-static without it breaking other parts of your program, this could work. If you can't, then you cannot avoid a cast.

like image 179
Pablo Avatar answered Sep 27 '22 23:09

Pablo