在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子句创建可抛出的自定义类,您需要扩展throwable类。

class MyException extends Throwable{

   MyException(String msg){

      super(msg);

   }

}

因此,如果需要抛出泛型类型的对象,则应该能够从中扩展Throwable类。但是,如果尝试这样做,则会生成编译时错误。因此,您不能使用throws子句抛出Generic类的对象。

示例

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

以上是 在java中可以抛出泛型类的对象吗? 的全部内容, 来源链接: utcz.com/z/345661.html

回到顶部