Problem during dynamic casting

Hi Guys,

Need you help

Situation is like this ?I have a function which accept the Sting parameter

Which is actually a full name of class ?using reflection I created the class and object

Now I want to cast this newly created object to their original class type

Code is somehow like this

Public void checkThis (String name) throws Exception{

Class c = Class.forName(name.trim());

Object o = c.newInstance();

System.out.println(" class name = " + c.getName());

throw ()o; //// here I want to cast this object to their orginal class type

/**

I tried throw (c.getName())o;

But it is not working

*/

}

[699 byte] By [ravindra_cyprusa] at [2007-11-27 3:43:51]
# 1
Have you tried throw (Class.forName(name.trim()))o; instead of throw (c.getName())o; ?
sztyopeka at 2007-7-12 8:47:28 > top of Java-index,Java Essentials,Java Programming...
# 2

You are trying to do the impossible, for example, this just doesn't work:

String classname = ...

Class cls = Class.forName(classname);

Object obj = cls.newInstance();

classname x = (classname) obj; //? There is no way to name this legal syntax!

Solution: you must statically know an interface or superclass for the dynamic class:

Runnable r = (Runnable) obj;

new Thread(r).start(); //etc

Or work with the Object reference, using reflection to apply methods, etc.

Message was edited by:

DrLaszloJamf

DrLaszloJamfa at 2007-7-12 8:47:28 > top of Java-index,Java Essentials,Java Programming...