Question about Java Generators

Is it possible to write a method that could instantiate any given type?

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

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

Can anyone help me?

+3
source share
3 answers
 public <U> U genericFactory(Constructor<U> classConstructor, Object..args)
  throws
   InstantiationException,
   IllegalAccessException,
   IllegalArgumentException,
   InvocationTargetException {
     return classConstructor.newInstance(args);
 }

You can get the constructor from the object Class<U>using the method getConstructors. Using the constructor itself, you can get information about the arguments, so additional code outside the factory must be added to fill out the corresponding arguments.

Obviously, this is just as ugly as Peter answered.

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

There are several problems with this method:

  • the class must have a constructor with no arguments
  • , , getObject throws.

. Class.newInstance().

+9

I highly recommend using the factory interface, if at all possible, rather than abusing reflection.

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

Source: https://habr.com/ru/post/1718092/


All Articles