I'm writing a function that will iterate on some collection , I don't know what collection I'm getting , so I wrote this till now
void PrintFieldsOfClass(Object obj){
if(obj ==null){
return;
}
Class<?> mainClass = obj.getClass(); // create instance of the class
Class<?>[] interfaces =null;
Object collection = null;
int isCollection = 0; //1 - for List , 2 - For Set , 3 - Map
if(mainClass !=null ){
interfaces = mainClass.getInterfaces();
}
try {
if(interfaces!=null ){
for(Class<?> interface1 : interfaces ){
if(interface1.getName().toString().equals("java.util.List")) {
isCollection = 1;
collection = new ArrayList<Object>();
}
else if(interface1.getName().toString().equals("java.util.Set")){
isCollection=2;
collection = new HashSet<Object>();
}
else if(interface1.getName().toString().equals("java.util.Map")){
isCollection=3;
collection = new HashMap<Object,Object>();
}
}
}
`
After I know what collection I got , how do I cast the object to that collection ? How do I iterate over it ? Thanks in advance !
Aucun commentaire:
Enregistrer un commentaire