gpt4 book ai didi

java - 有没有办法创建 Class 的实例,该实例将 Class 作为构造函数中传递泛型的参数

转载 作者:行者123 更新时间:2023-12-02 08:51:38 25 4
gpt4 key购买 nike

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)

对于上述编译器会抛出错误,因此我最终将其转换为 Map<String,byte[]> .

最佳答案

您不能使用 Class 执行此操作对象,因为您无法获得 Class<Map<String, byte[]>> ,只有一个Class<Map> .

但是如果你使用例如,你可以做到这一点一个Supplier<T>相反:

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);

或者,如果您实际上不需要创建 T 的新实例,但可以使用某种“原型(prototype)”对象:

class JsonSerializer<T> {
public JsonSerializer(T instance){
this.instance = instance;
}
}

Serializer<Map<String, byte[]>> serializer = new JsonSerializer<>(ImmutableMap.of());

关于java - 有没有办法创建 Class<T> 的实例,该实例将 Class 作为构造函数中传递泛型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com