gpt4 book ai didi

java - 如何将泛型参数传递给方法?

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

我正在尝试存储作为抽象类的子类的对象,但这里有一个问题:

abstract class Letter {
public void store_object(Letter letter) {
HashMap<Class<? extends Letter>, ? extends Letter> map = new HashMap<>();
map.put(letter.getClass(), letter); <-- this line throws an error
}
}
class A extends Letter {}
class B extends Letter {}

map.put 抛出错误的原因是 letter 不是 Letter 的子类(它是信件).

有没有办法将方法参数更改为 Letter 的通用子类?像这样的东西:

public void store_object(? extends Letter letter) {

public void store_object(Object<? extends Letter> letter) {

错误是:

no suitable method found for put(Class<CAP#1>,NewClass19.Letter)
method Map.put(Class<? extends NewClass19.Letter>,CAP#2) is not applicable
(argument mismatch; NewClass19.Letter cannot be converted to CAP#2)
method AbstractMap.put(Class<? extends NewClass19.Letter>,CAP#2) is not applicable
(argument mismatch; NewClass19.Letter cannot be converted to CAP#2)
method HashMap.put(Class<? extends NewClass19.Letter>,CAP#2) is not applicable
(argument mismatch; NewClass19.Letter cannot be converted to CAP#2)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends NewClass19.Letter from capture of ? extends NewClass19.Letter
CAP#2 extends NewClass19.Letter from capture of ? extends NewClass19.Letter

最佳答案

我真的不确定你想在这里做什么,但这将使你的代码编译:

abstract class Letter {
public <T extends Letter> void store_object(T letter) {
HashMap<Class<? extends Letter>, T> map = new HashMap<>();
map.put(letter.getClass(), letter); // <-- this line throws an error
}
}
class A extends Letter {}
class B extends Letter {}

为什么要生成一个新的 HashMap每次 store_object方法被调用?你真正的问题是什么?请阅读What is the XY problem?

相关:Canonical Java Generics FAQ


顺便说一下,Object<Anything>总是错的,因为 Object未参数化。


所以我看到了您的编辑,仅供引用:

private static HashMap<Class<? extends Test>, Test> map = new HashMap<>();

static void addTest(Test test) {
map.put(test.getClass(), test);
}

你的问题到底是什么?

关于java - 如何将泛型参数传递给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497514/

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