cutthecrap said:
Yep, I get that bit, the advanced idea of a "Factory" pattern is not beyond
my 20 years Object Oriented experience.
String clssName = "SasDMImp";
Naming.set("rmi:" + host + reg, Class.forName(clssName).newInstance());
But you were asking about object casting, not object creation?
You wanted to dynamically cast something like
SomeClass obj = (clssName) Naming.lookup("rmi/" + host + reg);
MY POINT is that in that line you no longer need be concerned with the
dynamic class name, since you ALREADY KNOW what you need to cast to, so
just do it:
SomeClass obj = (SomeClass) ... blah blah
I'm afraid you don't understand. From the OP's earlier message:
====================================================================
From (e-mail address removed) Thu Aug 26 20:13:04 2004
From: Glenn Robinson <
[email protected]>
Subject: Re: Invalid cast type error
Newsgroups: comp.lang.java.help,comp.lang.java.programmer
Followup-To: comp.lang.java.help
Date: Thu, 26 Aug 2004 10:14:57 +0100
(snip)
I have:
interface DataManager
class SasDMImp which implements DataManager
I do the following:
String dmClassName = "SasDMImp";
Class dmClass = Class.forName(dmClassName);
I now want to use the SasDMImp class to cast a new object and this is the
part I'm having trouble with.
If I hard code the class name I use:
SasDMImp dm = (SasDMImp) Naming.lookup("rmi://" +host + registry);
I want to replace the hard coded SasDMImp with dmClass but I get the Invalid
Cast type when I do this.
=========================================================================
Note the last paragraph: "I want to replace the hard coded SasDMImp with
dmClass". This is a very strong implication that he wants a situation
where you DO NOT necessarily already know which clas to cast to.
Otherwise he would be just fine using hardcoded classnames and not
bothering us about it. He already knows how to do so - he said it
above.
In Java, you CAN NOT cast anything to a type which you do not already
know. Variable types must be known at compile time. There is no way
around this.
Fortunately, in the OP's case, he can very well use the DataManager
interface to cast the object to, like I suggested. That would be, hey,
I don't know, THE WHOLE POINT OF THE INTERFACE, and stuff.