Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Typecasting from Java.lang.Object to an instance of a custom Class

Tags:

java

stack

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.

like image 581
Hari Avatar asked Feb 09 '12 02:02

Hari


People also ask

Can you typecast an object in Java?

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 do I resolve Java Lang ClassCastException error?

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.

How can we convert one class object to another class in Java?

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.

How do you cast an object to class?

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.


2 Answers

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>();
like image 70
James Montagne Avatar answered Sep 22 '22 10:09

James Montagne


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
like image 29
Steven Schlansker Avatar answered Sep 22 '22 10:09

Steven Schlansker