java - How to instantiate a HashMap<K, V>? -
first of all, i'm not expert of generics, attempted create class persist type of object specified path using following approach.
public class persistentobject<t> { /** * persisted object class. */ private class<t> clazz; /** * persisted object. */ private t object; /** * path of file object persisted */ private string path; public persistentobject(string path, class<t> clazz) { this.clazz = clazz; this.path = path; load(); //load file or instantiate new object } }
it works fine, i'm not able use t
class implement interface map<k, v>
, because of clazz
constructor parameter. here i'm trying achieve:
persistentobject<string> test = new persistentobject<string>("path", string.class); persistentobject<hashmap<string, integer>> test2 = new persistentobject<hashmap<string, integer>>("path", hashmap<string, integer>.class); // compilation error
the problem how can pass class
object allows instantiation of hashmap<k, v>
, e.g. hashmap<string, integer>
, if there one?
i guess there design flaw in implementation, misunderstanding of generics concepts, or both. comments or suggestions welcome.
thanks in advance.
you using class literal pass class
object persistentobject
constructor. however, generics aren't supported in class literals, because in java generics compile-time feature. due type erasure, generic type parameters aren't available @ runtime, presumably when plan use class
object.
assuming need class
object instantiate hashmap
@ runtime, type information isn't available create hashmap<string, integer>
-- hashmap
.
to compile, can use unchecked cast.
persistentobject<hashmap<string, integer>> test2 = new persistentobject<>("path", (class<hashmap<string, integer>>) (class<?>) hashmap.class);
casting class<?>
class literal allowed without warning, you'll compilation warning casting class<hashmap<string, integer>>
. can use @suppresswarnings("unchecked")
remove warning. sure unchecked cast indeed safe purposes.
Comments
Post a Comment