johnny_kb
johnny_kb

Reputation: 714

create an Array of a Class with reflection and generic at runtime

I made this class ArrayBuilder with generics to make some basic operation to manage an array of T objects.

public class ArrayBuilder<T> {

@SuppressWarnings("unchecked")
public ArrayBuilder(Class<T> ct, int dim){
    container = (T []) Array.newInstance(ct, dim);
}

public T getElement(int index){
    return container[index];
}
public void setElement(int index, T value){
    container[index] = value; 
}
public T[] getContainer(){
    return container;
}

T[] container;

public static void main(String[] args) throws ClassNotFoundException {
    PrintStream ps = new PrintStream(System.out);
    Scanner sc = new Scanner(System.in);
    ps.print("che array desidera? ");
    String nameClass = "discover.";
    nameClass = nameClass + sc.nextLine();
    Class<?> toManipulate = Class.forName(nameClass);
    //Type type = toManipulate.getGenericSuperclass();
    ArrayBuilder<toManipulate> ab = new ArrayBuilder<toManipulate>(toManipulate, 10);

}

}

in main, program asks to the user to insert the name of the Class wich he prefers, so I want to use ArrayBuilder constructor to create this kind of array but compiler doesn't accept variable toManipulate in the angular brackets. Maybe Do I have to extract generic Type from the instance toManipulate?

Upvotes: 2

Views: 752

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533710

Generics are a compile time feature. What you have can equally be handled by raw types as you don't know what the type is at compile time.

Class toManipulate = Class.forName(nameClass);
ArrayBuilder ab = new ArrayBuilder(toManipulate, 10);

or if you really want to use generics you can do

Class<?> toManipulate = Class.forName(nameClass);
ArrayBuilder<?> ab = new ArrayBuilder<Object>(toManipulate, 10);

Upvotes: 1

Related Questions