dimanche 25 juin 2017

How to Use An Objects getClass() Method to set a generic type

Please take look at example code below:

Object o1= new Integer(4); 
ArrayList<Integer> list=new ArrayList<>();
list.add((Integer) o1);

Instead I'd Like to do something like:

Object o1= new Integer(4); 
ArrayList<o1.getClass().getSimpleName()> list=new ArrayList<>();
list.add((o1.getClass().getSimpleName()) o1);

o1.getClass().getSimpleName() returns "Integer" as a Java.lang.String object, my question is how can I embed this string into my code some how with reflection so the type of items in list can be determined at runtime. It is possible to do so by switch statement like:

Object o1= new Integer(4); 
switch(o1.getClass().getSimpleName()){
case "Integer":    
    ArrayList<Integer> list=new ArrayList<>();
    list.add((Integer) o1);
case "String":
    ...

.
.
.
}

but I hope there will be a better solution.





Aucun commentaire:

Enregistrer un commentaire