简体   繁体   中英

How do I pass generic type for java.lang.reflect.Array.newInstance?

My code snippet.

public class GenericArray <T extends Comparable<T>>{
   private T[] a;
   private int nElems;
   public  GenericArray(int max) // constructor
   {
       a=(T[])java.lang.reflect.Array.newInstance(Integer.class, max); 
       //Hard coded for Integer.
   }
}

GenericArray arr= new GenericArray<Integer>(100); 

This works, As I am instantiating explicitly passing Integer.class. How do I make this as generic ?

Or Is there a way to print Type information which passed to GenericArray using ParameterizedType ? (If I get that probably, I would handle using if statements)

Because of type erasure, you need to pass the Class<T> as an argument in the constructor, like

public GenericArray(Class<T> cls, int max) // constructor
{
    a = (T[]) java.lang.reflect.Array.newInstance(cls, max);
}

and pass the class in the constructor and please don't use a raw type when you use it. That is,

GenericArray<Integer> arr = new GenericArray<>(Integer.class, 100); 

You can parameterized your class by passing the type like:

GenericArray<String, Integer> myobj = new GenericArray<>(“John”,2); 

Or

Consider the given code in which generic method display(), that accepts an array parameter as its argument.

class GenericArray <T extends Comparable<T>>
    {    
    public<T> display(T[] val) {       
    for( T element : val)     
    {             
     System.out.printf(“Values are: %s “ , element);    
    }   
    }
    // Declaring Array
    GenericArray[] intValue = {1, 7, 9, 15};                
    GenericArray<Integer> listObj = new GenericArray<> (); 
    // Passing Array values               
    listObj.display(intValue);

Similarly, You can declare a class with two type parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM