我真的很想喜欢泛型,但到目前为止,它们带来的麻烦超过了任何好处。请,请向我展示我错了。
我理解在使用无泛型框架(Spring、Hibernate)时添加 @SuppressWarnings("unchecked") 的必要性。这本身就大大降低了泛型的价值,还需要传递类到构造函数中以避免擦除的问题。然而,真正的难点似乎总是在转换上。我通常会尝试一段时间来正确使用语法,但最终放弃纯粹的尝试,添加 @SuppressWarnings 并继续我的生活。
以下是一个例子:我正在反射一个 bean 来查找两个实例之间的差异。某些属性实现了 Comparable,使得 (a.equals(b) == false) 但 (a.compareTo(b) == 0)(例如 BigDecimal、Date)。在这些情况下,我希望将属性视为相同。
MyObject original = getOriginal();
MyObject updated = getUpdated();
for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(MyObject.class)) {
// Assume I'm putting in the try/catch block
Object pOriginal = pd.getReadMethod().invoke(original, (Object[]) null);
Object pUpdated = pd.getReadMethod().invoke(updated, (Object[]) null);
boolean isPropertySame;
if (Comparable.class.isAssignableFrom(pOriginal.getClass())) {
// Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable<T> should be parameterized
isPropertySame = Comparable.class.cast(pOriginal).compareTo(Comparable.class.cast(pUpdated)) == 0;
// The method compareTo(capture#19-of ?) in the type Comparable<capture#19-of ?> is not applicable for the arguments (capture#21-of ? extends Comparable)
Comparable<?> comparable = Comparable.class.cast(pOriginal);
isPropertySame = comparable.compareTo(comparable.getClass().getTypeParameters()[0].getGenericDeclaration().cast(pUpdated)) == 0;
// Even if I get the generics right, I still get an error if pOriginal is java.sql.Timestamp and pUpdated is java.util.Date (happens all the time with Hibernate).
isPropertySame = (help);
} else {
isPropertySame = pOriginal.equals(pUpdated);
}
if (!isPropertySame) {
PropertyDelta delta = new PropertyDelta(pd, pOriginal, pUpdated);
dao.save(delta);
}
}
你有什么想法可以放到(帮助)中吗?
Timestamp
和Date
存在的问题是一个众所周知的问题:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4631234。它已经在Java 6中修复(可能也在5u6中修复)。 - notnoop