Instant parameter generation

I am learning Java generic, I am catching some kind of problem creating an instance of a type obtained from general parameters (this is possible in C # though)

class Person { public static <T> T say() { return new T; // this has error } } 

I tried this: generics in Java - instantiating T

 public static <T> T say(Class<?> t) { return t.newInstance(); } 

Error:

 incompatible types found : capture#426 of ? required: T 

This does not work. The following example looks fine, but it entails creating an instance of a class, cannot be used by the static method: Creating an instance of type generics in java

 public class Abc<T> { public T getInstanceOfT(Class<T> aClass) { return aClass.newInstance(); } } 

Is this a Java type wipe language? Is this a limitation of type erasure?

What is the work around this problem?

+6
source share
1 answer

You were very close. You need to replace Class<?> (Which means "class of any type") with Class<T> (which means "class of type T"):

 public static <T> T say(Class<T> t) throws IllegalAccessException, InstantiationException { return t.newInstance(); } 
+8
source

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


All Articles