Java generics - getting type

Duplicate: creating generic type in java

Hello! I am a C # guy giving Java a try .. since I would do the following in java.

in c #

public T create_an_instance_of<T>(){
  T instance = default (T);
 // here usually some factory to create the implementation
   instance =  some_factory.build<T>();
 // or even..
   instance = some_factory.build(typeOf(T) );

 return instance;
}
+3
source share
4 answers

Java generators are based on the erase dash . This allows them to be compatible down, but means that you cannot use the type parameter itself because it does not exist at run time.

The closest you can do is the following:

public <T> T create_an_instance_of(Class<T> c){
    return c.newInstance(); // or use constructors via reflection
}
+5
source

You cannot do this in Java because generics are not protected. You can use the so-called "type tokens", but it has limitations.

 static <T> T construct(Class<T> klazz) {
     try {
        return klazz.newInstance();
     } catch (InstantiationException e) {
        return null;
     } catch (IllegalAccessException e) {
        return null;
     }
 }

 System.out.println(construct(String.class).isEmpty()); // prints "true"

Class<?>.newInstance() , (, nullary).

0

Try something like:

public static <T> T createInstance(Class<T> clazz)
        throws IllegalArgumentException, SecurityException,
        InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    T ans = clazz.getConstructor().newInstance();
    return ans;
}
0
source

The right choice is to use the abstract Factory. Just pass it in and it will even be able to instantiate classes that don't have open no-arg constructors or the corresponding implementation class of the interface class.

Reflection is absolutely unnecessary and the wrong choice is here.

0
source

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


All Articles