首页 > 解决方案 > 什么是 Java 中的未经检查的调用?

问题描述

public class Main<T> {
     T obj;
     public Main(T input) {
         this.obj = input;
     }
     void set(T input) {
         this.obj = input;
     }
     void print() {
         System.out.println(this.obj);
     }
    public static void main(String[] args) {
        Main<Integer> tester = new Main<>(2);
        Main test = tester;
        test.print();
        test.set(3);
        test.print();
    }
}

在上面的代码中,test.set(3) 给了我一个警告“未经检查地调用 'set(T)' 作为原始类型 'Main' 的成员”。什么是未经检查的调用,为什么我会得到它,即使 set 方法有效并且在执行 print 语句后,会打印 3。

标签: javagenericscalluncheckedparameterized-types

解决方案


Main您还没有告诉编译器该test变量指的是哪种类型。就编译器而言,它可能是Main<Integer>orMain<String>Main<RahatsCrazyClass>。所以编译器不能保证这test.set(3)是有道理的——你可能试图IntegerMain<String>.

警告告诉您编译器遇到了无法保证感觉的情况。你应该避免有这种事情。test声明为 aMain<Integer>比声明为 a更好Main


推荐阅读