0

I want to know how to cast a String into my own class the way org.json.JSONObject does.

You can cast the String: {"key":"value"} as a JSONObject even though JSONObject inherits only from Object.

How do i get a String to cast as a MyOwnClassObject while only inheriting from Object?

sheepy
  • 1
  • some generics magic i guess. certainly doable whatcha got thus far? – Caffeinated Jan 15 '15 at 00:29
  • 1
    What you're asking is not possible. Casting rules aren't negotiable: the candidate variable must be [assignable from](http://stackoverflow.com/questions/3949260/java-class-isinstance-vs-class-isassignablefrom) the target type. If not, your code will not compile. And if the cast type is not assignable from the runtime type of the candidate variable, the result is a `ClassCastException`. References [Assignment Conversion](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.2) and [Casting Conversion](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.5). – gknicker Jan 15 '15 at 00:58

1 Answers1

7

new JSONObject(str) is not a cast, it is just a normal constructor.

If you want to implement such a thing, just define a constructor for your class that takes a single String.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • [JSONObject(String) constructor documentation](http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject(java.lang.String)) – gknicker Jan 15 '15 at 00:32