gpt4 book ai didi

java - 为什么 java 需要将有界类型参数实例化为其上限类?

转载 作者:行者123 更新时间:2023-12-02 09:09:07 27 4
gpt4 key购买 nike

Java 需要将有界类型参数实例化到其上界类才能进行强制转换,例如:

<T extends Integer> void passVal (T t) {
Integer number = 5;
t = (T) number; // Without cast a compile error is issued
}

T 在声明时已经被限制为 Integer 或其子类之一(我知道,没有任何子类),在我看来,任何有界的类型参数只能实例化为其上限类或其子类之一,那么为什么需要强制转换?

此外,我知道如果我通过在此方法之外的调用实例化参数,情况并非如此,因此不要将其作为答案提供;该问题特定于在其声明类/方法中实例化的有界类型参数。

最佳答案

T 并不意味着 Integer,它必须对 Integer 或从其扩展的任何类有效。假设 StrangeInteger 从 Integer 扩展,并将 T 替换为 StrangeInteger:

void passVal (StrangeInteger t) {
Integer number = 5;
t = (StrangeInteger) number;
}

它尝试将 Integer 变量分配给 StrangeInteger 变量,除非 number 首先是 StrangeInteger 或派生类,否则无法执行此操作。事实上,你的代码应该(概念上)在运行时抛出异常,除非 t 是一个整数,但在这种情况下,由于类型删除,它实际上不会这样做(请参阅编辑 2)。

情况类似于:

Object obj = "Hello"
String t = (String)obj; // this will not fail, but requires a cast

Object obj2 = getDBConnection();
String t2 = (String)obj2; // this will fail at runtime

编辑:Integer确实是最终的,所以T只能是Integer,但编译器可能没有检查上限是否是最终的,毕竟上限是最终的没有什么意义,所以允许特殊情况会增加复杂性,但实际 yield 却很少。

编辑2:TL; DR:您混淆了上限和下限,但是类型删除有一些警告。一旦您使用泛型而不是仅使用基本类型进行任何值得做的事情,这种情况就会崩溃。

英语不是我的母语,所以我可能不太清楚。

我认为您正在努力解决使用带有上限的泛型类型和仅使用上限作为类型之间的区别。泛型(来自 C++ 和其他语言)的思想是,如果将 T 替换为边界允许的任何类型 T,则代码必须有效,因此您不能调用上界中未定义的任何方法。

A 是 T 的上限也意味着您始终可以将 T 对象分配给 A 变量。您无法安全地将 A 对象分配给 T 变量(除非 A == T),只有当 A 是 T 的下限而不是上限时,您才能这样做。另请参阅Understanding upper and lower bounds on ? in Java Generics.

Java使用type erasure实现泛型,there are a few advantages ,但这会导致一些并不总是显而易见的限制。由于这种情况下的类型删除,在类型检查 T 被类型删除步骤中的上限替换之后,转换本身不会失败,即 (T)number 被 (Integer)number 替换。如果您执行任何导致对子类进行强制转换的操作(例如,如果您返回更改后的 t 并将结果分配给子类的变量),仍然会发生异常,因为编译器会添加隐式强制转换。

如果您调用依赖于 T 子类的方法(这是一种常见模式),这也会失败,例如:

List<Person> persons = ...
Comparator<Person> nameComparator = (p1,p2) -> p1.getName().compareTo(p2.getName())
java.util.Collections.sort(persons,nameComparator);

以下代码示例显示了几种情况下的行为。我对所有内容都使用 System.err 以避免输出中的顺序问题。

import java.util.function.Consumer;
import java.util.function.Function;

class A {
@Override public String toString(){ return "A";}
public String foo(){ return "foo";}
}

class B extends A {
@Override public String toString(){ return "B";}
public String bar(){ return "bar";}
}

class C extends B { }

public class Main {

public static void main(String[] args) {
Function<A,String> funA = a -> a.foo();
Function<B,String> funB = b -> b.bar();
Function<C,String> funC = c -> c.bar();
Consumer<B> ignoreArgument = b -> {
System.err.println(" Consumer called");
};

B b = new B();
System.err.println("* voidTest *");
voidTest(b);
System.err.println("------------");
System.err.println("* returnTest *");
returnTest(b);
System.err.println("returnTest without using result did not throw");
System.err.println("------------");
try {
System.err.println("Returned " + returnTest(b).toString());
System.err.println("returnTest: invoking method on result did not throw");
}
catch(Exception ex) {
System.err.println("returnTest: invoking method on result threw");
ex.printStackTrace();
}
System.err.println("------------");
B b2 = null;
try {
b2 = returnTest(b);
System.err.println("returnTest: assigning result to a B variable did not throw");
}
catch(Exception ex) {
System.err.println("returnTest: assigning result to a B variable threw");
ex.printStackTrace();
}
System.err.println("------------");
System.err.println("* functionTest funA *");
functionTest(b, funA);
System.err.println("------------");
System.err.println("* functionTest funB * ");
functionTest(b, funB);
System.err.println("------------");
System.err.println("* consumerTest *");
consumerTest(b, ignoreArgument);
// The following won't work because C is not B or a superclass of B
// Compiler error functionTest(T, Function<? super T,String>) is not applicable for the arguments (B, Function<C,String>)
// functionTest(b, funC);
}

private static <T extends A> void voidTest(T t){
System.err.println(" Before: " + t.toString());
t = (T)new A(); // warning Type safety: Unchecked cast from A to T
System.err.println(" After: " + t.toString());
}

private static <T extends A> T returnTest(T t){
System.err.println(" Before: " + t.toString());
t = (T)new A();
System.err.println(" After: " + t.toString());
return t;
}

private static <T extends A> void functionTest(T t, Function<? super T,String> fun) {
System.err.println(" fun Before: " + fun.apply(t));
t = (T)new A();
try {
System.err.println(" fun After: " + fun.apply(t));
}
catch(Exception ex) {
System.err.println(" fun After: threw");
ex.printStackTrace();
}
}

private static <T extends A> void consumerTest(T t, Consumer<? super T> c) {
System.err.print(" Before: ");
c.accept(t);
t = (T)new A();
try {
System.err.println(" After: ");
c.accept(t);
System.err.println(" c.accept(t) After: worked");
}
catch(Exception ex) {
System.err.println(" c.accept(t) After: threw");
ex.printStackTrace();
}
}
}

OpenJDK 11 下的输出是:

* voidTest *
Before: B
After: A
------------
* returnTest *
Before: B
After: A
returnTest without using result did not throw
------------
Before: B
After: A
returnTest: invoking method on result threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
at Main.main(Main.java:35)
------------
Before: B
After: A
returnTest: assigning result to a B variable threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
at Main.main(Main.java:45)
------------
* functionTest funA *
fun Before: foo
fun After: foo
------------
* functionTest funB *
fun Before: bar
fun After: threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
at Main.functionTest(Main.java:83)
at Main.main(Main.java:57)
------------
* consumerTest *
Before: Consumer called
After:
c.accept(t) After: threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
at Main.consumerTest(Main.java:97)
at Main.main(Main.java:60)

我不完全确定 resultTest 如果结果被完全忽略,为什么没有引发异常,也许在这种情况下语言不需要强制转换,或者编译器删除了它。调用结果上限中定义的方法仍然会导致异常。最后,consumerTest 的一个观察结果是,它不需要调用 bar() 来引发 ClassCastException,它只需要将 t 传递给需要 B 参数的消费者。

关于java - 为什么 java 需要将有界类型参数实例化为其上限类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58126534/

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