I want to make a generic class which stores a pool of temporary objects (such as 2D vector Vec2d ) so that I don't have to dynamically allocate them during my simulations. Based on these answers [1] [2] I come to this solution:
import java.lang.reflect.Array;
class TempPool<T>{
T[] objs;
public TempPool(Class<T> c, int n) {
T[] a = (T[])Array.newInstance(c, n); // initialize the array
try{ // Compiler forces me to use try fo handling
for(int i=0; i<n; i++) a[i]=(T)c.newInstance(); // initialize fields in the array
}catch(Exception e){
System.out.println("Exception thrown :" + e +" in TempPool()" );
}
objs = a;
}
T borrow( ){ return objs[icur++]; };
void repay(T o){
if( o != objs[icur] ) objs[-1]=null; // Throws exeption
}else{ icur--; }
}
But when I try to use
class Vec2d{ double x,y; }
tmpVec2d = new TempPool (Vec2d.class,10); // tried both
//tmpVec2d = new TempPool<Vec2d>(Vec2d.class,10); // tried both
it it throws exception Exception thrown :java.lang.InstantiationException: Boulders_rigid$Vec2d in TempPool()
Aucun commentaire:
Enregistrer un commentaire