我有一个小问题。我编写了一个函数,该函数应该为对象列表生成表(可以是日期或自定义一个或任何一个)。该函数的参数是“列表列表”和“列表标题”。那么,问题来了,为什么是这一行
if (value.getClass().isInstance(Date.class) ...
不执行,即使当我打印 value.getClass() 时也显示:class java.util.Date。还有一个问题,如何检查“value”是否是List?预先非常感谢:)
这是部分代码:
for (Object o : list) {
List<String> atributes = new ArrayList<String>();
for (java.lang.reflect.Field field :o.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(o);
if (value != null) {
if (value.getClass().isInstance(Date.class)) {
atributes.add(convertDateToString((java.util.Date) value));
}
atributes.add(value.toString());
}
} ...
最佳答案
您滥用了 Class#isInstance
,如果 Date.class
是 value.getClass()
的实例,则返回 true:
Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language
instanceof
operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
相反,您想要:
if(value instanceof Date)
或
if(Date.class.isInstance(value))
关于java - 获取对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30928158/