有没有办法找到一个字段在Java反射中是否是boolean
和isPrimitive()
?
Field fieldlist[] = clazz.getDeclaredFields();
for (int i = 0; fieldlist.length & gt; i; i++) {
Field fld = fieldlist[i];
if (fld.getClass().isPrimitive()) {
fld.setInt(object, 0);
continue;
}
}
if(fld.getType().equals(boolean.class))
刚刚测试了这一点,它适用于基元boolean
变量。
我相信Boolean.class.isAssignableFrom(fld.getClass())
可以用于确定字段是否为布尔值。不过,我还没有机会测试这是否适用于原语。
试试这个(参考):
public boolean getBoolean(Object obj)
throws IllegalArgumentException,
IllegalAccessException
Gets the value of a static or instance boolean field.
Parameters:
obj - the object to extract the boolean value from
Returns:
the value of the boolean field
Throws:
IllegalAccessException - if the underlying field is inaccessible.
IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), **or if the field value cannot be converted to the type boolean** by a widening conversion.
NullPointerException - if the specified object is null and the field is an instance field.
ExceptionInInitializerError - if the initialization provoked by this method fails.
这是用于基元和对象的:
boolean isBooleanType = field.getType().equals(boolean.class) || field.getType().equals(Boolean.class);