Java 反射获取字段数据类型:使用 Field.getType() 方法
可以使用 Field 类的 getType() 方法获取字段的数据类型。例如:
Field field = MyClass.class.getField('myField');
Class<?> fieldType = field.getType();
if (fieldType == int.class) {
// 字段类型为 int
} else if (fieldType == String.class) {
// 字段类型为 String
} else if (fieldType == boolean.class) {
// 字段类型为 boolean
} else {
// 其他类型
}
需要注意的是,基本数据类型在反射中的 Class 对象是对应的包装类,例如 int 对应的是 Integer.class,boolean 对应的是 Boolean.class,因此需要使用 == 进行判断。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ofOk 著作权归作者所有。请勿转载和采集!