jeudi 27 février 2020

Instantiating an object of a type parameter using reflections

I know that when working with Generics we can't instantiate an object of unknown type i.e the statment : T var = new T() will give compile time error , I tried it using Reflections after some search , but its not compiling and gives me the error I will mention at the end

Code :

public class HelloWorld{
     public static void main(String []args){
        Pair<Integer> obj = new Pair<Integer>(Integer.class);
                            obj.<Integer>func();             
    }
}
class Pair<T>
{
    T  var;
   <T> Pair(){}
   <T> Pair(Class<T> reflection){
             var = reflection.newInstance() ;  
             }

   <T> void func(){
   System.out.println(var);
   }
}

Error :

HelloWorld.java:12: error: incompatible types: T#1 cannot be converted to T#2
             var = reflection.newInstance() ;  
                                         ^
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in constructor <T#1>Pair(Class<T#1>)
    T#2 extends Object declared in class Pair

I am trying to find the cause of the error but can't reach it





Aucun commentaire:

Enregistrer un commentaire