java - Passing Class to a method to instantiate a generic -


the following code doesn't work, because marked line not compile:

myclass {     //singleton stuff     private static myclass instance;     private myclass () {}     public static myclass getinstance() {         if(instance==null) {             instance = new myclass ();         }         return instance;     }      // method creating problems     public nongenericsuperclassofgenericclass create(class<?> c1, class<?> c2) {         return new genericclass<c1,c2>; // not compile!!!     } } 

i not want myclass generic. why? because actual implementation of method create similar following:

    // method creating problems     public nongenericsuperclassofgenericclass create(class<?>... classes) {         if(somecondition)              return new genericclass<classes[0],classes[1]>;         else              return new othergenericclass<classes[0]>; } 

therefore, cannot couple myclass particular generics. there way instantiate genericclass passed parameters? how?

thanks


thank answers. i'll tell whole story.

i'm using spring , plan use mongodb.

the class genericclass like:

 genericclass<persistettype1, long>  

or

 genericclass<persistenttype2, long> 

where persistenttype1/2 classes need store in db, while, genericclass sort of proxy access mongo apis. in fact, looks like:

  public mongotemplate gettemplate();   public void save(t toinsert);   public list<t> select(query selectionquery);   public t selectbyid(id id);   public writeresult update(query selectionquery, update updatedattributes);   public void delete(t toremove);   public void delete(query selectionquery); 

now, what? controllers (or entity, if picky) need instantiate repository , invoke methods. causes controllers coupled mongodb, i.e. explicitly have instantiate such genericclass, called mongorepository , strictly dependent on mongo (in fact generic 2 "degrees of freedom").

so, decided create myclass, further proxy isolates controllers. in way, controller can single instance of myclass , let create new instance of appropriate repository. in particular, when "somecondition" true, means want use mongorepository (when false, maybe, need instantiate hibernate proxy, i.e. hibernaterepository). however, mongorepository generic, therefore requires form of instantiation, hoped pass parameter.

unfortunately, generics resolved @ compile time, don't work me, guess.

how can fix that?

that doesn't make sense, in java.

the whole point of generics specify @ compile-time types are.

if don't know types until runtime, java generics useless, due type erasure. (in c#, need reflection)


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -