Torque_Roll
Torque_Roll

Reputation: 11

Java.lang.Class.cast doesn't return a casted object

I am trying to cast an object to its superclass using Java.lang.Class.cast but I get the same object. What can be the reason?

This is the code I'm running:

public static void parse(Object obj)
{
    // parse all super classes
    Class<?> clazz = obj.getClass().getSuperclass();
    if (!clazz.equals(prevClass))
    {
        prevClass = clazz;
        Object castedObj = clazz.cast(obj);
        parse(castedObj);   
    }
    fillObject(obj);
}

but when passing to parse an object of dynamic type B, where B extends A, castedObj is equal to obj. But I want castedObj to be a new object of dynamic type A because the parse method relies on that fact (iterates on the fields of the dynamic type class).

Upvotes: 0

Views: 121

Answers (1)

Stephen C
Stephen C

Reputation: 718788

I am trying to cast an object to its superclass using Java.lang.Class.cast but I get the same object.

That is exactly what is supposed to happen.

For reference types, a cast is simply a type check. For example:

  A a = (A) b;

This says to check that b is-a A and the assign the reference so that we can refer to it as an A using a.

There is no object conversion going on. No creation of new instances. The value assigned to a is identical in every respect to the value in b.

The same also applies when you use reflection to do the typecasting.

Or to put it another way, the value returned by getClass() for a given object is always going to be the same ... no matter how you cast is.


It is not clear what you are trying to do in your code, but it we assume that fillObject is filling in fields that relate to a particular class, then you most likely need to pass the Class as an explicit parameter. The true class of obj is always going to be the object's actual class ... irrespective of any casting.

Upvotes: 2

Related Questions