如何找出每个对象在 ArrayList<Object> 中的类型? [英] How do I find out what type each object is in a ArrayList<Object>?
本文介绍了如何找出每个对象在 ArrayList<Object> 中的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由从数据库导入的不同元素组成的 ArrayList,由字符串、数字、双精度和整数组成.有没有办法使用反射类型技术来找出每个元素保存的每种类型的数据?
I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?
仅供参考:有这么多类型的数据的原因是这是一段 Java 代码,正在编写以使用不同的数据库实现.
FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.
推荐答案
在 C# 中:
已根据 的建议修复麦克
ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
if (o is int) {
HandleInt((int)o);
}
else if (o is string) {
HandleString((string)o);
}
...
}
在 Java 中:
ArrayList<Object> list = ...;
for (Object o : list) {
if (o instanceof Integer)) {
handleInt((Integer o).intValue());
}
else if (o instanceof String)) {
handleString((String)o);
}
...
}
这篇关于如何找出每个对象在 ArrayList<Object> 中的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文