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.
You should write code using generics. For example instead of
you can let the stack know about the type of object within:
If for whatever reason this isn’t feasible, you can cast: