• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class.cast()  RSS feed

 
Nibin Jacob Panicker
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
appreciate if someone could explain the diffrence in the following 2 ways of casting an object.

1) Object a = new MyObject();
MyObject b = (MyObject)a;

2) Object a = new MyObject();
MyObject b = MyObject.class.cast(a);

Which one should i use ?
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your Java version is 1.4.2 are older user Option 1. If your version is 1.5 you can use both the option.
 
Nibin Jacob Panicker
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Prabhu.
i am using jdk5.0
are there any performance issues with either of the casting ? or both are the same.
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
seems like both are same. But I'm not sure about this. sorry.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
About the question "Which one should i use ?": Use the first syntax, because this is the usual syntax for casting that's built-in into the language.

Don't use obscure syntax because you believe that this makes your program perform better unless you have a very good reason to do so (for example because your program has a real performance issue and you know that this is the cause of it).
 
Chris Beckey
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The object.class.cast() syntax will perform worse than the simple (class) cast syntax. The code below includes the byte-code (from javap) in the comments, note that the class.cast() syntax invokes the cast() method in addition to checking the casting. The class.cast() method simply checks that it is a compatible type (throws ClassCastException if not) and then does a simple cast to the parameterized type.
I'd use the simple cast unless I had some compelling reason not to. Maybe somebody knows some obscurity in casting that would make the class.cast() safer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!