Lakshmi
Lakshmi

Reputation: 21

Is there a way to create an instance of a Class<T> which takes in Class as a parameter in constructor passing generics

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

Answers (1)

Andy Turner
Andy Turner

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

Related Questions