I need to do cast on an object and to transform it to a type, determined by the value of a variable. But when I do cast gives an error me, it says to me that it is not a type. My code:
newType = //read the type of a file c = Class.forName(nClase); cons = c.getConstructors();
//I NEED TO MAKE a DYNAMIC CAST NOW, MUST BE ABLE TO CHOOSE the OBJECT CLASS THAT IS
obj = (newType) cons[0].newInstance(aux); // I WANT THAT IT TAKES THE VALUE OF THE VARIABLE, THAT IT IS A TYPE. BUT HE DOES NOT DO IT.
The Vector class implements several interfaces, each of which you can cast a Vector object to.
Cloneable c = (Cloneable) v; Collection c2 = (Collection ) v; List list = (List) v; RandomAccess ra = (Cloneable) v; Serializable s = (Cloneable) v;
Stack is a subclass of Vector. The following will cause an error, because every Vector object is NOT a Stack. (You can't "down-cast".) Stack stack = (Stack)v;
BUT
every Stack is a Vector because Stack inherits FROM Vector.
So, if:
Stack stack = new Stack();
you can cast a Stack object into a Vector object like:
Vector vector = (Stack)stack;
In this case you can "up-cast".
Figure out what all this means and I am sure you can write some if then else blocks to do the job and get it done correctly.
I didn't want use if-else because i have many types. But i think i must use it. Because the cast is checked at compile time and the variable get value at run time. So the dinamyc cast is impossible.