eric2323223
eric2323223

Reputation: 3628

Java generics question

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?

Upvotes: 3

Views: 400

Answers (3)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147134

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

public interface MyFactory<T> {
     T newInstance();
}

Upvotes: 8

Carl
Carl

Reputation: 7544

 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.

Upvotes: 8

Peter Štibran&#253;
Peter Štibran&#253;

Reputation: 32893

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.

Upvotes: 9

Related Questions