java - Casting with NewInstance -


i need make cast 1 type another. googled stucked. want cast initobject casted class.

object objinstance = initobject.getclass().newinstance();                     casted str=(casted)objinstance; 

why make classcastexception?

casting requires class casted must subclass or subinterface of class initobject. example:

list<string> list = new arraylist<string>(); arraylist<string> castedlist = (arraylist<string>) list; //works integer int = (integer) list; // throws classcastexception 

an alternative casting helper method convert related objects. such example collections.toarray method.

casting discouraged telling compiler know type casted object is, , of course wrong.


Comments