简体   繁体   中英

Java Cast Object to Derived Class From Provided Instance

How do I cast an object to its derived class? Why does the below have a problem with casting as (object.getClass()) ?

public Object convertObjectToItsOwnClass(Object object) {
     object = (object.getClass()) object;
     return object;
}

So the above code should pass an instance of Foo back rather than passing an instance of Object back when Foo foo is sent to it.

object.getClass() will give you Object type. But out is of type String so you will get Type mismatch compile type error.

After looking your comment If I pass the method Person person then it should use the toString method @Override in Person class. This can be done as below:

public String objectToStringConverter(Object object) {
     String out = object.toString();
     return out;
}

This will call toString method of your Person class.

It is not possible to use a dynamic Classname in a cast statement! And besides that it would not make much sense. At runtime Java knows of what type your object is, so there is no sens in casting it to that class.

If you want your code to react differently to different subclasses then you can use the instance of construct:

if (object instanceof MyClass) {
  MyClass myObject = (MyClass) object;
  //... 
}

If you only want to know which class the object is from, you can get its classname like this:

String className = object.getClass().getName();

EDIT:

It is not necessary to cast to the subclass. As mentioned before Java already knows about the subclass. See:

class A {}
class B extends A {}

public class Demo {

    public static void main(String[] args) {
        Object a = new A();
        Object b = new B();
        System.out.println(a.getClass().getName()); //prints A
        System.out.println(b.getClass().getName()); //prints B
    }

}

The result of toString() is of type String , so there is no need to cast in the example you provided. However, to answer your question, if you want to cast from one type to another and you know when writing your code (ie at compile-time) what the type is to which you wish to cast the object, then put the type in parens:

   Object untypedObject = // ...
   String typedObject = (String) untypedObject;

The code above does the cast from type Object to type String (throwing a ClassCastException as a result). There is also another method of casting (albeit less commonly used) when you don't know what the intended type is when writing your program (ie you don't know the indented type until runtime). Example:

   Class<?> runtimeClass = // ...
   Object untypedObject = // ...
   Object typedObject = runtimeClass.cast(untypedObject);

With the code above, you still have an Object on the left-hand side; however, the use "runtimeClass.cast()" ensures that the object is actually of the given runtime type (throwing an exception if it isn't).

String className = object.getClass().getName();

This will give you the name of the class.

object.toString();

This will give you the toString representation of the object. Provided it's implemented by the object that is passed in the method. Remember if toString() method is not implemented by the object you passed in it will print the hashcode of the object. Which is default functionality of java.

Ok as per the latest comments from ThreaT if you want to cast it to the actual object type at runtime here is what you will have to do. I can provide you with a code sample later on weekend.
But here is the approach.

Once the class name is found than create a class dynamically and load it. Dynamically created class will have a method that will check for instance of at runtime and return you the Casted object. But having said that I am not sure what will be the practical use. If you can wait until weekend I can send you a sample. Or give it a shot yourself :). I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM