Is there a way to typecast from Java.lang.Object to an instance of a custom defined class.
Essentially, I have created a Stack (java.util.Stack) and have pushed into it instances of type my_class. But when I pop out from the Stack, I receive an instance of type Java.lang.Object.
Do I have to create a constructor in my_class that can create my_class instances from Java.lang.Object ?
Generics is the best way to go. I am pretty new to Java, and without realizing about generics (same as in C++ STL), I have been doing a lot of typecasting like-
to convert to an integer: new Integer((Java.lang.Object).toString()).intValue()
Guess those days are gone now :) Thanks for making my life easy.
In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java.
How to handle ClassCastException. To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.
gson. Gson for converting one class object to another. First convert class A's object to json String and then convert Json string to class B's object. Save this answer.
The cast() method of java. lang. Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object.
You can cast the object like this:
my_class myObj = (my_class)obj;
But if you define your stack as a stack of my_class
then you don't need to bother with casting:
Stack<my_class> myStack = new Stack<my_class>();
You should write code using generics. For example instead of
MyObject someObj = ...;
Stack myStack = new Stack();
myStack.push(someObj);
someObj = myStack.pop(); // Error!
you can let the stack know about the type of object within:
MyObject someObj = ...;
Stack<MyObject> myStack = new Stack<MyObject>();
myStack.push(someObj);
someObj = myStack.pop(); // Now this works!
If for whatever reason this isn't feasible, you can cast:
MyObject someObj = ...;
Stack myStack = new Stack();
myStack.push(someObj);
someObj = (MyObject) myStack.pop(); // This works too, but is considered very bad style
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With