【发布时间】:2011-10-25 06:25:56
【问题描述】:
如何判断 Collection 中的类是什么类型?我需要以不同于处理复杂类型的方式处理简单数据类型,因此我必须知道包含的类。目前,我必须遍历集合以找出听起来不正确的类。这个link 很有帮助,但没有完全解决我的问题。基本上,这里有以下问题: 1.如何确定集合内的类? 2. 如何判断对象是java包装类(Integer、String、Date等)还是专有类(Student、Vehicle等)。
谢谢 贾巴瓦巴
entity = new SomeObject();
Class entityClass = entity.getClass();
for (Method method : entityClass.getDeclaredMethods()) {
Class<?> returnType = method.getReturnType();
if (returnType != null) {
if (returnType.isPrimitive() || (returnType.getName().startsWith("java.lang.")) || (returnType == java.util.Date.class)) {
// handling primitive and wrapper classes
handleScalar(method);
} else if (Collection.class.isAssignableFrom(returnType)) {
Collection collection = (Collection) method.invoke(entity);
if (collection == null || collection.isEmpty()) {
continue;
}
for (Object value : collection) {
if (value.getClass().getName().startsWith("java.lang.") || (value.getClass() == java.util.Date.class)) {
handleSimpleVector(method);
// no need to go through all the simple values
continue;
} else {
// Each 'value' is itself a complex object.
handleComplexObject(method);
}
}
} else if (<return-type-is-an-Array>){
// do something similar as the above.
}
}
}
【问题讨论】:
-
根据您发布的代码,您已经成功了。那么你试图完成什么,你在什么时候卡住了?
-
@Platvoet。我试图区分 return 类型: (a) public long getDistance(); (b) 公共列表
getCounts(); (c) public List getCars(); (d) public Long[] getSizes();因为我正在为 Lucene/Solr 编写一个包装器,并且我需要知道访问器的返回类型来决定我应该使用哪种 Solr 字段。 -
你想要完成什么?我觉得有更好的方法,而您只是使用了错误的工具。
-
让我重新表述一下,就像 Amir 一样,我想知道这段代码的目的是什么。为什么需要区分这些方法?可能会有更适合您需求的不同方法。
-
所以您基本上只想在 Lucene 中存储任何类?在这种情况下,您可能会考虑使用 java 的可序列化系统。提供您自己的 ObjectInputStream 和 ObjectOutputStream。
标签: java