[680] in java-interest
Re: Class.newInstance() question
daemon@ATHENA.MIT.EDU (Chuck McManis)
Thu Jul 13 03:04:55 1995
Date: Wed, 12 Jul 1995 22:43:14 -0700
From: cmcmanis@scndprsn.Eng.Sun.COM (Chuck McManis)
To: Anselm.Baird_Smith@inria.fr, java-interest@java.Eng.Sun.COM
The best way to do this is to define an interface that objects you want
to create this way can use. Thus you would define:
public interface Loadable {
public Object make(String parameter);
}
And then in objects you were instantiating you would use:
Class foo = Class.forName("MyCustomClass");
return ((Loadable)(foo.newInstance()).make("Some parameter"));
Now you could also protect it like this:
Object x;
try {
x = (Loadable) (foo.newInstance()).make("Some Parameter");
} catch (Exception e) {
// didn't work , probably doesn't implement loadable
x = null;
}
return (x);
So if the object you were instantiating couldn't be made loadable it wouldn't.
You would write a loadable object like so:
class Bletch implements Loadable {
/** MUST have a null constructor if you want newInstance to work */
public Bletch(){
}
public Bletch(String xyzzy) {
}
public Bletch make(String fooey) {
return new Bletch(fooey);
}
}
A bit of overhead but it gets the job done.
--Chuck
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com