java 如何判断类型
判断基本数据类型
使用 instanceof 关键字可以判断对象是否为某个类的实例。例如:
Object obj = "Hello";
if (obj instanceof String) {
System.out.println("obj is a String");
}
判断包装类类型
对于包装类(如 Integer、Double),同样可以使用 instanceof:
Object num = 123;
if (num instanceof Integer) {
System.out.println("num is an Integer");
}
使用 getClass() 方法
通过 getClass() 获取对象的运行时类,再与目标类比较:

Object value = 3.14;
if (value.getClass() == Double.class) {
System.out.println("value is a Double");
}
检查数组类型
判断数组类型需注意数组的维度,例如:
Object arr = new int[]{1, 2, 3};
if (arr instanceof int[]) {
System.out.println("arr is an int array");
}
处理泛型类型擦除
由于泛型在运行时会被擦除,直接判断泛型类型不可行。可通过传递 Class<T> 参数辅助判断:

public <T> void checkType(T obj, Class<T> type) {
if (type.isInstance(obj)) {
System.out.println("obj matches the type");
}
}
反射获取类型信息
通过反射获取字段或方法的类型信息:
Field field = MyClass.class.getDeclaredField("fieldName");
Class<?> fieldType = field.getType();
System.out.println("Field type: " + fieldType.getName());
使用 Class.isPrimitive()
检查是否为基本数据类型(如 int、boolean):
Class<?> clazz = int.class;
if (clazz.isPrimitive()) {
System.out.println("clazz is a primitive type");
}
结合 Class.isAssignableFrom()
判断类或接口的继承关系:
if (List.class.isAssignableFrom(ArrayList.class)) {
System.out.println("ArrayList is a subclass of List");
}






