Java Class.cast() vs. cast operator

2009-10-12T23:47:47

Having being taught during my C++ days about evils of the C-style cast operator I was pleased at first to find that in Java 5 java.lang.Class had acquired a cast method.

I thought that finally we have an OO way of dealing with casting.

Turns out Class.cast is not the same as static_cast in C++. It is more like reinterpret_cast. It will not generate a compilation error where it is expected and instead will defer to runtime. Here is a simple test case to demonstrate different behaviors.

package test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;


public class TestCast
{
    static final class Foo
    {
    }

    static class Bar
    {
    }

    static final class BarSubclass
        extends Bar
    {
    }

    @Test
    public void test ( )
    {
        final Foo foo = new Foo( );
        final Bar bar = new Bar( );
        final BarSubclass bar_subclass = new BarSubclass( );

        {
            final Bar bar_ref = bar;
        }

        {
            // Compilation error
            final Bar bar_ref = foo;
        }
        {
            // Compilation error
            final Bar bar_ref = (Bar) foo;
        }

        try
        {
            // !!! Compiles fine, runtime exception
            Bar.class.cast( foo );
        }
        catch ( final ClassCastException ex )
        {
            assertTrue( true );
        }

        {
            final Bar bar_ref = bar_subclass;
        }

        try
        {
            // Compiles fine, runtime exception, equivalent of C++ dynamic_cast
            final BarSubclass bar_subclass_ref = (BarSubclass) bar;
        }
        catch ( final ClassCastException ex )
        {
            assertTrue( true );
        }
    }
}

So, these are my questions.

  1. Should Class.cast() be banished to Generics land? There it has quite a few legitimate uses.
  2. Should compilers generate compile errors when Class.cast() is used and illegal conditions can be determined at compile time?
  3. Should Java provide a cast operator as a language construct similar to C++?

Copyright License:
Author:「Alexander Pogrebnyak」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/1555326/java-class-cast-vs-cast-operator

About “Java Class.cast() vs. cast operator” questions

Having being taught during my C++ days about evils of the C-style cast operator I was pleased at first to find that in Java 5 java.lang.Class had acquired a cast method. I thought that finally we ...
Based on this oracle doc example I try create own example to test it. Of course referenced example work as suggested. But when I try base on Class.cast method I have a problem: My code is CL3 ex...
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()
I was looking through new intrinsic methods in Java 9 and found that now the method Class.cast is intrinsic too along with Class.isInstance. I did simple benchmark to check that: @BenchmarkMode(M...
I have a Person class, which implements Cloneable. I then have Objects p and o which reference a Person object. I am trying to clone one into another, and discovered that the following works: Obje...
I am writing a generic method which will validate a property by trying a class.cast on it but I keep getting a ClassCastException ... Class to Test public <T> T get(Properties p, String pro...
I am currently developing a Minecraft plugin that should be able to manage mobs. In short, in any case, I want my plugin to be a maximum multi-version, so I use Reflector. but when I use Class.cast(
I'm working on a data manager that can manage user-created Java data models. It has a getter method to return all objects of a given class: public <T> Collection<T> getAllForClass(Cla...
Whats the difference between using Class.cast to convert an object to a certain type v/s doing the same using ObjectMapper.convertValue. I am assuming cast also internally uses jackson but I think ...
I am trying to debug an issue involving a ClassCastException in Java. In the interest of solving the issue I need to know what is going on when I cast from Object to a specific type. Can anyone exp...

Copyright License:Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.