> T newInstance = (T)cl.newInstance();
I would avoid Class.newInstance. It passes exceptions from the
constructor straight through, even those it does not declare itself. So
checked exceptions become unchecked. If you stick to the long route via
java.lang.reflect.Constructor, then you should stay safe and obvious.
Tom Hawtin

Signature
Unemployed English Java programmer
http://jroller.com/page/tackline/
R - 18 Apr 2006 17:41 GMT
to tell the truth I haven't thought of thrown exceptions.
good point!
but I'm new to Java and I'm missing something
class Class has get(Declared)Constructor(Class[] args) method
but default constructor doesn't have any parameters - I tried to pass
null and 'new Class[] {}' as parameter but I couldn't get this
constructor.
In both situations I caught NoSuchMethodException:
Exception in thread "main" java.lang.NoSuchMethodException:
mypackages.testing.DAOFactory.<init>()
Method class has invoke method, but I haven't seen any
create/make/instantiate method in Constructor class.
Can you give a simple example of instantiating object from Constructor
class?
thanks in advance
best regards
R
> cl = Class.forName(name, true, ClassLoader.getSystemClassLoader());
[...]
> but I agree it's too over-engineered ;)
;-) It is a little...
Also, by hardwiring the choice of classloader you are making it unusable for
classes which should be loaded by custom classloaders. That might not matter
at all for your application, but many application frameworks (Servelet
containers and the like) load all application classes via custom classloaders,
so you might find yourself in trouble. I would recommend against using
reflection at all (for this), but at minimum you should change it to read just
cl = Class.forName(name);
in which case the classloader that loaded your Pool class will be used -- which
is, at least, less likely to be wrong.
If you /must/ go this route (either out of need, or out of stubbornness ;-)
then you should have the code that creates the Pool pass the class object
itself, rather than the class's name, to the constructor.
public class Pool<T>
{
public
Pool(Class<T> cl)
{
...
(Incidentally, there's nothing to be gained by naming the thing "GenericPool",
it /is/ generic, so there's no need to reiterate that in the name. You don't
see Java's standard Collection classes with names like
java.util.GenericList<T>...)
Alternatively, you could create a helper interface which defines a factory
object that the pool will use:
public interface
PoolEntryFactory<T>
{
T create(); // NB: no checked exceptions allowed !
}
public class Pool<T>
{
public
Pool(PoolEntryFactory<T> factory)
{
for (i = 0; i < 10; i++)
pool.add(factory.create());
...
But I think you'll agree that this is getting to be more bother than it's
worth.
-- chris