javacavaj
javacavaj

Reputation: 2961

Java Data Binding and Custom Converter

I'm attempting to bind an AtomicBoolean to the "enabled" property of a JCheckBox. Since an AtomicBoolean is not a replacement for a Boolean I'm using a custom Converter. However, the Converter shown below results in a ClassCastException. Why?

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);
            }
        });

Resulting Exception

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)

Upvotes: 1

Views: 2312

Answers (1)

Ryan Stewart
Ryan Stewart

Reputation: 128749

That exception isn't coming from your code. It's happening here:

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);
}

There are a couple of different maven artifacts that have that class in it with a call to Class.cast() on line 1312. It doesn't much matter which you're using. You'll probably need to do some debugging. Put a breakpoint on that line, and then you can trace the call back and see what values are being passed down and why the exception is happening. It seems that your converter isn't being used for some reason, which is probably the problem. It's probably trying to cast AtomicBoolean to Boolean.

Upvotes: 1

Related Questions