我正在尝试将AtomicBoolean绑定到JCheckBox的“enabled”属性。由于AtomicBoolean不是布尔的替代品,我使用的是自定义转换器。但是,下面显示的转换器会导致ClassCastException。为什么呢?
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, isIdle, org.jdesktop.beansbinding.ObjectProperty.create(), cornerCb, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
binding.setConverter(new Converter<AtomicBoolean, Boolean>() {
@Override
public Boolean convertForward(AtomicBoolean value) {
Boolean b = value.get();
return b;
}
@Override
public AtomicBoolean convertReverse(Boolean value) {
return new AtomicBoolean(value);
}
});
产生的异常
java.lang.ClassCastException
at java.lang.Class.cast(Class.java:2990)
at org.jdesktop.beansbinding.Binding.convertForward(Binding.java:1312)
at org.jdesktop.beansbinding.Binding.getSourceValueForTarget(Binding.java:844)
at org.jdesktop.beansbinding.Binding.refreshUnmanaged(Binding.java:1222)
at org.jdesktop.beansbinding.Binding.refresh(Binding.java:1207)
at org.jdesktop.beansbinding.Binding.refreshAndNotify(Binding.java:1143)
at org.jdesktop.beansbinding.AutoBinding.bindImpl(AutoBinding.java:197)
at org.jdesktop.beansbinding.Binding.bindUnmanaged(Binding.java:959)
at org.jdesktop.beansbinding.Binding.bind(Binding.java:944)
at org.jdesktop.beansbinding.BindingGroup.bind(BindingGroup.java:143)
答案 0 :(得分:1)
该异常不是来自您的代码。它发生在这里:
private final TV convertForward(SV value) {
if (converter == null) {
Class<?> targetType = noPrimitiveType(targetProperty.getWriteType(targetObject));
return (TV)targetType.cast(Converter.defaultConvert(value, targetType));
}
return converter.convertForward(value);
}
有一些不同的maven工件在其中包含该类,并且在第1312行调用了Class.cast()。使用它并不重要。您可能需要进行一些调试。在该行上放置一个断点,然后您可以跟踪回调并查看传递的值以及异常发生的原因。似乎您的转换器由于某种原因未被使用,这可能是问题所在。它可能试图将AtomicBoolean强制转换为Boolean。