5

I am working on a generic class and I want to use Class.cast() to do some casting to avoid those nasty unchecked cast warnings or the @SupressWarning annotation on the methods.

I think Class.cast() should be basically the same thing as casting directly. But like all reflection methods, it might not be the case. Does anyone know the exact different between them?

billc.cn
  • 7,187
  • 3
  • 39
  • 79
  • 3
    see http://stackoverflow.com/questions/243811/when-should-i-use-the-java-5-method-cast-of-class – Crozin May 10 '12 at 09:17
  • I am with you regarding your emotions about all those warnings, but what I do to get rid of them is simply make the Eclipse compile ignore them at the project level. – Marko Topolnik May 10 '12 at 09:17
  • 1
    You may want to take a look at : [http://stackoverflow.com/questions/1555326/java-class-cast-vs-cast-operator](http://stackoverflow.com/questions/1555326/java-class-cast-vs-cast-operator) – Michael Laffargue May 10 '12 at 09:18
  • 2
    You can try "tricks" to avoid unchecked cast warnings, but using constructions like `Class.cast()` is not going to make casting safer. You can still get `ClassCastException`s at runtime. So you might be creating a false sense of safety with this. – Jesper May 10 '12 at 09:24
  • @Jesper Hopefully if my class is implemented correctly ClassCastException will never occur. I am only doing these casts because of an external collection-like class that is not generic. So far, from the replies, it seems the only difference is the virtual method invocation (which is acceptable) and some static optimisations that can't be done (which is also acceptable) and since it's designed to be used in generics, I guess it should be fine to use in my case. – billc.cn May 10 '12 at 09:39
  • 1
    @Jesper, a bit late to the party, but using `Class.cast()` has the benefit of checking the cast at the place where the unchecked cast would be, so your stack trace will be more clear than a strange invisible cast happening at the caller’s site. – Didier L Feb 24 '23 at 13:55

1 Answers1

6

I recommend using Class.cast() over @SuppressWarnings where possible.

Don't care about performance here. If you have performance issues, profile your application, and I would be very surprised if this turned out to be a hot spot.

Puce
  • 37,247
  • 13
  • 80
  • 152