gpt4 book ai didi

java - 实例化 T 的子类时如何返回泛型类型 T

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

我想要一个参数化类,它能够返回 T 类型的对象和 T 的子对象

这是代码:

import java.lang.reflect.InvocationTargetException;

class A {};

class B extends A {};

public class testGenerics<T extends A> {

T a;

T getA() {
return getA(B.class); // Compilation problem:
//The method getA(Class<T>) in the type testGenerics<T> is not applicable for the arguments (Class<B>)
}

T getA(Class<T> clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
return clazz.getConstructor().newInstance();
}

}

我是这样想的:

我声明泛型类型 T,它扩展 A。因此,我可以从 Class clazz 创建扩展 A 的类型 T 的实例。

但是,当我决定从 B.class 获取 A(它扩展了 A)时:

getA(B.class)

我收到以下错误:

The method getA(Class< T >) in the type testGenerics< T > is not applicable for the arguments (Class< B >)

这是为什么呢?我该如何修复它?

最佳答案

你的问题是类定义class testGenerics<T extends A> .

这意味着T在创建该类的实例时定义,可以绑定(bind)到 A 的任何子类- 这可能不是B但是C等等。从而通过B.class不保证匹配。

要解决这个问题,请输入 T 的定义在方法级别:

<T extends A> A getA(Class<T> clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
return clazz.getConstructor().newInstance();
}

//No generics needed here, since the method above returns A anyways.
//If it'd return T you'd have to change the return type here to B since getA(B.class) binds T to be B now
A getA() throws Exception {
return getA(B.class);
}

自方法级别T隐藏类级别的定义,您需要对此采取措施:使用不同的名称(例如 S )或删除类级别的定义(无论如何,它没有多大意义)。

关于java - 实例化 T 的子类时如何返回泛型类型 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49408978/

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