[英]Reflection , java , iterate on collection
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 , the PrintFieldsOfClass will get some object or collection of objects and I will have to print the fields of the class , I have it working for some class , want to add collection support.我正在编写一个将迭代某个集合的函数,我不知道我得到了什么集合,所以我写了这个直到现在,PrintFieldsOfClass 将得到一些对象或对象集合,我将不得不打印字段在班级中,我有它为某个班级工作,想要添加集合支持。
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>();
}
}
}
` `
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 !
提前致谢 !
Have you tried something like:您是否尝试过类似的事情:
void printFieldsOfClass(Object obj) {
if (obj == null) {
return;
}
// Deal with collections...
if (obj instanceof Collection) {
for (Object o : ((Collection<Object>) obj)) {
printFieldsOfClass(o);
}
return;
}
// Otherwise it is a 'simple' object...
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>();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.