在 Java 中声明泛型(类型)的限制
java 8object oriented programmingprogramming更新于 2025/11/7 11:56:17
泛型是 Java 中的一个概念,它允许类、接口和方法接受所有(引用)类型作为参数。换句话说,它允许用户动态地选择方法(类的构造函数)接受的引用类型。通过将类定义为泛型,您可以使其成为类型安全的,即它可以作用于任何数据类型。
泛型的限制
您不能以以下列出的某些方式和场景使用泛型 −
- 您不能将原始数据类型与泛型一起使用。
class Student<T>{
T age;
Student(T age){
this.age = age;
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
Student<String> std2 = new Student<String>("25");
Student<int> std3 = new Student<int>(25);
}
}
编译时错误
GenericsExample.java:11: error: unexpected type Student<int> std3 = new Student<int>(25); ^ required: reference found: int GenericsExample.java:11: error: unexpected type Student<int> std3 = new Student<int>(25); ^ required: reference found: int 2 errors
- 您无法实例化通用参数。
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();
T obj = new T();
}
}
编译时错误
GenericsExample.java:15: error: cannot find symbol T obj = new T(); ^ symbol: class T location: class GenericsExample GenericsExample.java:15: error: cannot find symbol T obj = new T(); ^ symbol: class T location: class GenericsExample 2 errors
- 泛型类型参数不能是静态的。
class Student<T>{
static 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();
}
}
编译时错误
GenericsExample.java:3: error: non-static type variable T cannot be referenced from a static context static T age; ^ 1 error
- 您不能将一种数据类型的参数化类型转换为另一种数据类型。
import java.util.ArrayList;
public class Generics {
public static void main(String args[]) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(25);
list1.add(26);
ArrayList<Number> list2 = list1;
}
}
编译时错误:
Generics.java:8: error: incompatible types: ArrayList<Integer> cannot be converted to ArrayList<Number> ArrayList<Number> list2 = list1; ^ 1 error
- 您无法创建泛型类型对象的数组。
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>[5];
}
}
输出
GenericsExample.java:12: error: generic array creation Student<Float>[] std1 = new Student<Float>[5]; ^ 1 error
泛型类无法扩展 throwable 类,因此您无法捕获或抛出这些对象。
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

