dimanche 4 janvier 2015

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?






Aucun commentaire:

Enregistrer un commentaire