简体   繁体   English

Java-下垂的ClassCastException

[英]Java - ClassCastException on downcast

i would try to write an JSONparser for gwt. 我会尝试为gwt编写一个JSONparser。

For this i use the lib org.json on server side and the com.google.gwt.json.client on client side. 为此,我在服务器端使用org.json库,在客户端使用com.google.gwt.json.client。

I build some interface's to call this two lib with the same methods. 我构建了一些接口,以使用相同的方法调用这两个库。

I use: 我用:

public class JSONObject extends com.google.gwt.json.client.JSONObject implements IJSONObject
{
  ...
}

and

public class JSONObject extends org.json.JSONObject implements IJSONObject
{
  ...
}

So it works like a sharm, but there is one thing i wouldn't get it. 因此,它的工作方式就像是一个道法,但有一件事我不会理解。

Client-side: 客户端:

JSONParser.parseLenient( sJson ).isObject()

Return ans Object from Type: "com.google.gwt.json.client.JSONObject" 从类型返回ans对象: “ com.google.gwt.json.client.JSONObject”

And i try to cast this to my custom JSONObject and get an ClassCastException. 我尝试将其强制转换为自定义JSONObject并获取ClassCastException。

My custom JSONObject extends from com.google.gwt.json.client.JSONObject and implements my IJSONobject. 我的自定义JSONObject从com.google.gwt.json.client.JSONObject扩展并实现了我的IJSONobject。

So if i can't cast the object, i can't user the interface. 因此,如果无法投射对象,则无法使用界面。

Thank you 谢谢

You will get ClassCastException for sure. 您肯定会得到ClassCastException。

Reason: 原因:

You are trying to cast an object "com.google.gwt.json.client.JSONObject" into an object "public class JSONObject extends com.google.gwt.json.client.JSONObject", which is not possible. 您正在尝试将对象“ com.google.gwt.json.client.JSONObject”转换为对象“公共类JSONObject扩展com.google.gwt.json.client.JSONObject”,这是不可能的。

Example: 例:

public class TestClassCast {

public static void main(String[] args) {

    A a = new A();
    B b = new B();

    A b1 = b; // This is possible since class B extends class A

    // B a1 = a; // This is not possible, which you are trying to do in your scenario.
}


}

class A {
    A(){};
}

class B extends A {
    B(){};
}

ClassCastException on downcast 垂头丧气的ClassCastException

I think you should extend from super class. 我认为您应该从超级班级扩展。 Please try this : 请尝试这个:

public class YourCustomJSON extends com.google.gwt.json.client.JSONValue implement IJSONobject
{
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM