Re: How should I re-write this?
Steven Simpson wrote:
On 26/03/10 09:36, Fencer wrote:
System.out.println(inst2);
....your only requirement on the loaded class is that it has the
toString() method on it, as specified by Object, so you probably ought
to write:
Object inst2 = MyTest.loadClass(Object.class, "action.SomeClass");
So you're no longer referring to action.SomeClass statically.
I think that the problem is expecting generics to do anything here.
Given that the OP is trying to get a "known class" out of a string, how
can he possibly do that? I think the should just admit that he can't
and make the caller deal with it.
public static Object loadClass( String className ) { ...
is how I would declare that method. It's basically the same as the
method Java provides on the Class object and, well, there's a reason for
that.
A more useful idea might be to assume that you have some type, some
interface, that your string-named class is going to implement. Then you
can at least check that the returned class implements that interface,
even if you don't know its exact type at runtime. So here's another
idea for "loadClass," which I've renamed here to make the example be a
bit more clear:
public static java.sql.Driver loadDB( String className ) {
T inst = null;
try {
ClassLoader cl = MyTest.class.getClassLoader();
Class<?> c = cl.loadClass(className);
inst = (java.sql.Driver)c.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return inst;
}
}