java: ClassCastException - [Ljava.lang.Long; cannot be cast to java.lang.Long

為{幸葍}努か 提交于 2020-01-24 05:15:08

问题


I use red5 and setting/getting attributes using the IConnection class, but that's really not relevant.

'L' means long in java. so 0L is 0 type Long instead of just '0' which is 0 type Integer.

What is the difference between [Ljava.lang.Long and java.lang.Long in the following error message:

stack trace: java.lang.ClassCastException: [Ljava.lang.Long; cannot be cast to java.lang.Long

update

code sample:

 static Long getLongAttribute(IConnection conn, String attribute) {
    Long result=null;
    try {
        if (!conn.hasAttribute(attribute))
            throw new Exception(attribute +  " - Long attribute not found!");
      result = conn.getLongAttribute(attribute); // <--- ERRROR ON THIS LINE
    } catch (Exception e) {
        _handleException(e);
    }
    return result;
}

回答1:


The first object is array of Long, the second is just Long. Try this

    Long l = 1l;
    Long[] l2 = {};
    System.out.println(l.getClass());
    System.out.println(l2.getClass());

Output

class java.lang.Long
class [Ljava.lang.Long;

But I do agree that [L_class_; presentation for array types is highly confusing. I wonder how it came to be that way.




回答2:


Your code try to cast Long[] to Long which causes ClassCastException




回答3:


[Ljava.lang.Long is a list of java.lang.Longs

EDIT: as noted below it's an array. Sorry, I typed too fast...




回答4:


I had similar problem where my code was

List<Object[]> rows = criteria.list();

But my criteria has just count(*) projection and hence criteria.list() returns just List<Long> instead of List<Long[]>

I resolved it by changing it to

List<Object> rows = criteria.list();



来源:https://stackoverflow.com/questions/4510354/java-classcastexception-ljava-lang-long-cannot-be-cast-to-java-lang-long

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!