Reputation: 21
class JsonSerializer<T> {
private Class<T> type;
public JsonSerializer(Class<T> type){
this.type = type;
}
}
Serializer<Map<String, byte[]>> serializer = new JsonSerializer<Map<String, byte[]>>(Map<String, byte[]>.class)
for above compiler throws an error and hence I end up casting later to Map<String,byte[]>
.
Upvotes: 2
Views: 71
Reputation: 140318
You can't do this with Class
objects because you can't obtain a Class<Map<String, byte[]>>
, only a Class<Map>
.
But you can do this if you use e.g. a Supplier<T>
instead:
class JsonSerializer<T> {
public JsonSerializer(Supplier<T> typeSupplier){
this.typeSupplier = typeSupplier;
// When you need an instance of `T`:
T instance = typeSupplier.get();
}
}
Serializer<Map<String, byte[]>> serializer = new JsonSerializer<>(HashMap::new);
or, if you don't actually need to create a new instance of T
, but instead can use some sort of "prototype" object:
class JsonSerializer<T> {
public JsonSerializer(T instance){
this.instance = instance;
}
}
Serializer<Map<String, byte[]>> serializer = new JsonSerializer<>(ImmutableMap.of());
Upvotes: 1