3

Is it possible to write a method that could create instances of any specified type?

I think java generics should help, so it might be something like this:

    public <U> U getObject(Class klass){
        //...
    }

Could anyone help me?

Svante
  • 50,694
  • 11
  • 78
  • 122
eric2323223
  • 3,518
  • 8
  • 40
  • 55

3 Answers3

9
public <U> U getObject(Class<U> klass) 
    throws InstantiationException, IllegalAccessException
{
    return klass.newInstance();
}

There are few `problems' with this method though:

  • class must have constructor with no arguments
  • if constructor throws any checked exception, it will be propagated even though your getObject method doesn't declare it in throws part.

See Class.newInstance() documentation for details.

Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116
  • 2
    The Class class was implemented with Generics, so there really is no need to wrap its own Generic `newInstance()` in another method. – akf Sep 19 '09 at 13:34
  • Yes, I agree. I just filled 'template' from question. – Peter Štibraný Sep 19 '09 at 15:07
  • Those are not problems; it is what it is. You have given the precise answer to the question. Add overloaded method getObject(Class clazz, Object...args) and it is done. – alphazero Sep 19 '09 at 18:25
8
 public <U> U genericFactory(Constructor<U> classConstructor, Object..args)
  throws
   InstantiationException,
   IllegalAccessException,
   IllegalArgumentException,
   InvocationTargetException {
     return classConstructor.newInstance(args);
 }

You can get a constructor from a Class<U> object via the getConstructors method. Via the constructor itself you can get information about the arguments, so there needs to be some extra code outside this factory to fill in the arguments appropriately.

Obviously, this is just as ugly as Peter's answer.

Carl
  • 7,538
  • 1
  • 40
  • 64
8

I strongly suggest using a factory interface if at all possible, rather than abusing reflection.

public interface MyFactory<T> {
     T newInstance();
}
Rich Seller
  • 83,208
  • 23
  • 172
  • 177
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • I agree that abusing reflection is undesirable, but with this solution you have another class for every class that a design needs manufactured or you have to have a member of a class before you ever manufacture others, since interface methods can't be static. – Carl Sep 19 '09 at 13:34
  • You can do it with a short anonymous inner class (perhaps assigned to a static final field, but because object creation is so fast that may even be a pessimisation. Having said that, the Java syntax does suck and JREs don't tend to be very memory efficient at handling many classes. – Tom Hawtin - tackline Sep 19 '09 at 13:41
  • @Tom, could you please explain this in more detail? – eric2323223 Sep 19 '09 at 17:33