我们可以在 Java 中抛出泛型类的对象吗?


泛型是 Java 中的一种概念,你可以用它启用类、接口和方法,将所有(引用)类型作为参数。换句话说,它是允许用户动态选择方法、类构造函数接受的引用类型的一种概念。通过将类定义为泛型,你使其类型安全,即它可以对任何数据类型起作用。

示例

 实例演示

class Student<T>{
   T age;
   Student(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Student<Float> std1 = new Student<Float>(25.5f);
      std1.display();
      Student<String> std2 = new Student<String>("25");
      std2.display();
      Student<Integer> std3 = new Student<Integer>(25);
      std3.display();
   }
}

输出

Value of age: 25.5
Value of age: 25
Value of age: 25

抛出泛型类对象

要创建可使用 throws 子句抛出的自定义类,你需要扩展可抛出类。

class MyException extends Throwable{
   MyException(String msg){
      super(msg);
   }
}

因此,如果你需要抛出一个通用类型的对象,你应该能够从其中扩展 Throwable 类。但是,如果你尝试这样做,将生成编译时错误。因此,你无法使用 throws 子句抛出泛型类对象。

示例

 实例演示

class Student<T>extends Throwable{
   T age;
   Student(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
   }
}

编译时错误

GenericsExample.java:1: error: a generic class may not extend java.lang.Throwable
class Student<T>extends Throwable{
                        ^
1 error

更新时间:09-Sep-2019

555 次浏览

开启 职业生涯

通过完成课程进行认证

开始
广告
© . All rights reserved.