java 将对象转换为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30007520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:17:28  来源:igfitidea点击:

convert object into date

javaobjectcastingjava.util.date

提问by Nono London

I get an ArrayListof Object[]from a database and I want to convert the java.sql.Datestored in an object into a java.util.Date(in order to use it in jfreechart): my code is as follows:

我从数据库中得到一个ArrayListof Object[],我想将java.sql.Date存储在一个对象中的对象转换为一个java.util.Date(以便在 jfreechart 中使用它):我的代码如下:

fills up the Array of object with data from MySQL

用来自 MySQL 的数据填充对象数组

 ArrayList<Object[]> mydata=new ArrayList<>(); 
 mydata=sqlGetter.getMdbObjectList(sqlString, null);


for(Object[] myobject : mydata){
        if (myobject[1].getClass()==java.sql.Date.class){
           java.util.Date mydate=null;
           mydate = Date ( myobject[1]);  
        } 
}

Netbeans return an error: "Java incompatible types: Object cannot be converted to Date"

Netbeans 返回错误:“Java 不兼容类型:对象无法转换为日期”

While I understand the idea, I would have expected to be able to cast the object into a Date after having checked that it is indeed of the right class.

虽然我理解这个想法,但在检查它确实是正确的类之后,我希望能够将对象转换为 Date。

I'm starting java, so please any helps on the obvious mistake that I must be doing would be useful.

我正在开始使用 Java,因此请对我必须做的明显错误提供帮助。

回答by Mureinik

You are missing a cast. Additionally, you'd be better off using the instanceofoperator:

你缺少演员。此外,您最好使用instanceof运算符:

for(Object[] myobject : mydata){
    // Note that java.sql.Date extends java.util.Date
    if (myobject[1] instanceof java.util.Date) {
        java.util.Date mydate = (java.util.Date) myobject[1];
    }
}

回答by Luthoz

you just need to explicit cast the object to Date ex: (Date) obj;

您只需要将对象显式转换为 Date ex: (Date) obj;