Java 泛型中的原始类型是什么?
java 8object oriented programmingprogramming更新于 2025/11/14 18:20:17
泛型是 Java 中的一个概念,它允许类、接口和方法接受所有(引用)类型作为参数。换句话说,它允许用户动态地选择类的方法、构造函数所接受的引用类型。通过将类定义为泛型,您可以使其成为类型安全的,即它可以作用于任何数据类型。
要定义泛型类,您需要在类名后的尖括号"<>"中指定所使用的类型参数,您可以将其视为实例变量的数据类型并继续执行代码。
示例 − 泛型类
class Person<T>{
T age;
Person(T age){
this.age = age;
}
public void display() {
System.out.println("年龄值: "+this.age);
}
}
用法 − 实例化泛型类时,需要在尖括号内指定类后的对象名称。因此,动态选择类型参数的类型,并将所需对象作为参数传递。
public class GenericClassExample {
public static void main(String args[]) {
Person<Float> std1 = new Person<Float>(25.5f);
std1.display();
Person<String> std2 = new Person<String>("25");
std2.display();
Person<Integer> std3 = new Person<Integer>(25);
std3.display();
}
}
原始类型
创建泛型类或接口的对象时,如果不指定类型参数,则它们被称为原始类型。
例如,如果在实例化 Person 类时遵循上述示例,则需要在尖括号中指定类型参数(类的类型)。
如果避免在尖括号中指定任何类型参数,并创建泛型类或接口的对象,则它们被称为原始类型。
public class GenericClassExample {
public static void main(String args[]) {
Person per = new Person("1254");
std1.display();
}
}
警告
这些代码编译时不会出错,但会生成如下所示的警告。
注意:GenericClassExample.java 使用了未经检查或不安全的操作。 注意:使用 -Xlint:unchecked 重新编译以了解详细信息。
以下是一些关于原始类型的注意事项 −
- 您可以将参数化(泛型)类型赋值给其原始类型。
public class GenericClassExample {
public static void main(String args[]) {
Person per = new Person(new Object());
per = new Person<String>("25");
per.display();
}
}
输出
Value of age: 25
- 如果将原始类型分配给参数化类型,将会生成警告。
public class GenericClassExample {
public static void main(String args[]) {
Person<String> obj = new Person<String>("");
obj = new Person(new Object());
obj.display();
}
}
Warning
Note: GenericClassExample.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
如果您的泛型类包含泛型方法,并且您尝试使用原始类型调用它,则会在编译时生成警告。
public class GenericClassExample {
public static void main(String args[]) {
Student std = new Student("Raju");
System.out.println(std.getValue());
}
}
警告
Note: GenericClassExample.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

