java - What method signature is appropiate returning a generic object? -


what should signature of method takes generic object , returns generic object, 1 either same or sub class of original class? is, if method takes generic class a, returned object guaranteed either a or b such b extends a (directly or indirectly)?

the code below exemplifies i'm trying do, in function getlist():

package com.company; import java.util.arraylist;  public class main {     private main(){          list<string> stringlist = new genericmessagelistcreator.getlist(stringgenericmessage.class);     }      private class genericmessagelistcreator() {         public list<genericmessage<t1>> getlist(class<t1 extends genericmessage> clazz) {             return new arraylist<t1>();         }     }      private class genericmessage<t> {         public genericmessage(){};         private t internalvalue;          public void setvalue(t value) {             this.internalvalue = value;         }          public void echovalue() {             system.out.println("i contain " + internalvalue);         }     }      private class stringmessage extends genericmessage<string>{}     private class integermessage extends genericmessage<integer>{} } 

example aside, in actuality i'm writing registry of classes used commands in command pattern. when object class want fetch appropriate command , pass object it.

i think looking signature:

public <t1 extends genericmessage> list<genericmessage<t1>> getlist(class<t1> clazz) {     return new arraylist<t1>(); } 

you'll find more info generic methods here.

edit

based on understand sample code, go (i corrected syntax errors in code):

private class genericmessagelistcreator {     public <u, v extends genericmessage<u>> list<u> getlist(class<v> clazz){         return new arraylist<u>();     } }  private class genericmessage<t> {     public genericmessage(){};     private t internalvalue;      public void setvalue(t value)     {         this.internalvalue = value;     }      public void echovalue() {         system.out.println("i contain " + internalvalue);     } }  private class stringmessage extends genericmessage<string>{} private class integermessage extends genericmessage<integer>{} 

thus, you'll able create list<string `stringmessage this:

list<string> stringlist = new genericmessagelistcreator().getlist(stringmessage.class); 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -