java - 获取对象实例?

标签 java object

我有一个小问题。我编写了一个函数,该函数应该为对象列表生成表(可以是日期或自定义一个或任何一个)。该函数的参数是“列表列表”和“列表标题”。那么,问题来了,为什么是这一行

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.classvalue.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/

相关文章:

php - 如何在 PHP 中从字符串数组创建对象

java - RestEASY 和 Jackson 不兼容 - NoSuchMethodException

java - 什么是好的嵌入式java应用服务器

c++ - 如何柯里化(Currying)对象上的方法以将其作为 C 风格回调传递?

javascript - 需要帮助加载带有用户输入的对象数组

Javascript 令人困惑的 null、instanceof 和 typeof 语法不一致?

Java地址簿。如何防止代码中出现重复的联系人?

java - 如何在 Eclipse 中使用相对路径读取和打印文件?

java - Java 时间戳的奇怪问题

java - 使用 ChannelExec 的命令未执行 - Jsch