ReadObject - NewInstance of unknown Object's

I have a Client/Server connection over sockets.

The server returns different types of Objects. I run the readObject method then, how can I instantiate the received class object ?

Seems to work fine when the Object is a String class but I receive the following error for java.io.file class:

java.lang.InstantiationException: java.io.File

at java.lang.Class.newInstance0(Class.java:293)

at java.lang.Class.newInstance(Class.java:261)

Code Example:

try{

Object o = connectionRef.readObject();

try{

Class c = Class.forName(new ro.util.string.GetWord(o.getClass().toString(),1).toString() );

Object co = c.newInstance();

System.err.println("Built Instance of Class=" + co.getClass().toString() );

}catch ( Exception e){

e.printStackTrace();

System.exit(1);

}

}catch ( Exception e ){

e.printStackTrace();

}

Message was edited by:

RobOsborne

[1381 byte] By [RobOsbornea] at [2007-11-27 11:41:58]
# 1

Not entirely convinced what you're doing makes sense - you send an object over the wire, query it for it's class's classname, load that class and then instantiate that class: most suspect - but hey ho, it's your code

In any case, the problem you're getting is due to the fact that Class.newInstance relies on the class having a no-args constructor, and java.io.File (which is what you're sending here) doesn't have one of those. There isn't a sure-fire "instantiate anything" method, either, since constructors can be of almost infinite flavours. What are you actually trying to achieve here?

georgemca at 2007-7-29 17:41:20 > top of Java-index,Core,Core APIs...
# 2

> I run the readObject method then, how can I instantiate the received class object ?

The readObject() method has already done that. You don't have to do anything more.

ejpa at 2007-7-29 17:41:20 > top of Java-index,Core,Core APIs...