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扩展并用StrangeInteger替换T:

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

它尝试将Integer变量分配给StrangeInteger变量,除非number最初是StrangeInteger或派生类,否则您不能这样做。实际上,除非t是一个整数,否则您的代码应在概念上(在概念上)在运行时引发Exception,但由于类型擦除,在这种情况下它实际上不会这样做(请参见编辑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

编辑:整数确实是最终的,所以T只能是整数,但是编译器可能没有检查上限是否是最终的,毕竟上限没有什么意义,因此允许添加特殊情况复杂性,几乎没有实际收益。

编辑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参数的使用者。

07-28 02:05
查看更多