gpt4 book ai didi

java - getClass 返回什么类型?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:54:59 25 4
gpt4 key购买 nike

这是我的代码:

Set<Class<Event>> s = new HashSet<>();             
Set<Class<? extends Event>> s2 = new HashSet<>();
Event e = new Event();

s.add(e.getClass()); // #1
s2.add(e.getClass()); // #2

class Event {
// ...
}

为什么编译器会在语句 #1 上引发错误?

我正在使用 Java 7。

最佳答案

如果你看一下documentation of getClass() method你会看到的

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0; 
Class<? extends Number> c = n.getClass();

所以 e.getClass() 的结果将是 Class<? extends Event>这正是Set<Class<? extends Event>> s2假设要存储。这就是为什么

s2.add(e.getClass());   // OK 

工作正常。


但在 Set<Class<Event>> s 的情况下事情有点不同。它只能存储Class<Event> .允许它存储来自 Class<? extends Event> 的对象就类型安全而言,引用将非常危险。

看看这个例子(为了更容易理解,我们将 Class 替换为 List,我们的 Action 实例将是 Animal ,就像 DogCat )。

List<Dog> dogs = new ArrayList<>(); 
List<? extends Animal> generalList = dogs;

Set<List<Animal>> set = new HashSet<>();

现在让我们假设 Set<List<Animal>> set可以储存List<? extends Animal>

set.add(generalList);

现在我们可以做一些可怕的事情了

for (List<Animal> animalList : set){
animalList.add(new Cat()); // I just placed Cat in container full of Dogs!
}

记住我们的List<Dog> dogs = new ArrayList<>();列表?现在它包含 Cat所以如果我这样做:

for (Dog dog : dogs){
dog.speak();
}

我可能会看到类似的东西

wof
woof
Woof
Meow! (psst: Get me out of here!)
...

或代替 Meow!一些异常(exception),如 NoSuchMethodException或者最有可能 ClassCastException: Cat cannot be cast to Dog .

因此,如您所见,允许这种机制并不是很明智。

关于java - getClass 返回什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29410827/

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