Flo
Flo

Reputation: 1207

Java - ClassCastException on downcast

i would try to write an JSONparser for gwt.

For this i use the lib org.json on server side and the com.google.gwt.json.client on client side.

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"

And i try to cast this to my custom JSONObject and get an ClassCastException.

My custom JSONObject extends from com.google.gwt.json.client.JSONObject and implements my IJSONobject.

So if i can't cast the object, i can't user the interface.

Thank you

Upvotes: 0

Views: 201

Answers (2)

Clement Amarnath
Clement Amarnath

Reputation: 5466

You will get ClassCastException for sure.

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.

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(){};
}

Upvotes: 2

Necromancer
Necromancer

Reputation: 919

ClassCastException on downcast

I think you should extend from super class. Please try this :

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

Upvotes: 0

Related Questions