开发者

Java casting implementation

I know how to use casting in Java but have a more specific question; could you please explain to me how the casting works (in memory)?

  • How is the variable typ开发者_StackOverflowe changed upon upcasting and downcasting?

  • How does the JVM know that it's safe to send this method to this object?

Thank you in advance.


Could you please explain me how the casting works ( in memory )?

It works at byte code level not really in memory

How the variable type is changed on upcasting and downcasting?

If it is a primitive with an special bytecode instruction, for instance from long to integer as in:

long l = ...
int i = ( int ) l;

The bytecode is: l2i if is a reference with the instruction checkcast

How the JVM knows that from this time it's safe to send this method to this object?

It doesn't, it tries to do it at runtime and if it fails throws an exception.

It is legal to write:

String s = ( String ) new Date();


Possible duplicate of the accepted answer to this question: How does the Java cast operator work?

There's also quite an extensive explanation here, that covers all data types, etc.: http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.5


All casting of primitives is done in registers (like most operations) For primitives, in many cases, when down casting the lower bits are taken and for up casting, the sign is extended. There are edge cases but you usually don't need to know what these are.


upcasting/downcasting a reference works the same in that it checks the actual object is an instance of the type you cast to. You can cast which is neither upcast nor down cast.

e.g.

 Number n = 1;
 Comparable c = (Comparable) n; // Number and Comparable are unrelated.
 Serializable s = (Serializable) c; // Serializable and Comparable are unrelated.


If you are interested in the inner workings of jvn concerning how casts work you may also check the jvm spec http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#25611

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜