Question

How do I use the BooleanConverter class???

The BooleanConverter class is final. But the method <T> T convertToType(Class<T> type, Object value) is protected... (why would they design it like that?)

I'm trying to do something like the following:

Converter converter = new BooleanConverter(Boolean.TRUE);
Boolean b = converter.convert(Boolean.TYPE, someMethodThatReturnsSomething());

Isn't the Converter's method <T> T convert(Class<T> type, Object value) supposed to return a Boolean object then.....?

However I'm getting the following compilation error:

Type mismatch: cannot convert from Object to Boolean

UPDATE:

With the repliers' answers, I was able to got it working. It seems like I had to explicitly add to my pom the latest commons-beanutils-core, since it was overriden by older dependency I had in my pom.xml.

This is how my pom looks now:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.1</version>
</dependency>

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils-core</artifactId>
    <version>1.8.3</version>
</dependency>

BTW, what I was trying to do is to find a way to execute non-boolean (non-void) methods from within an if predicate:

Converter converter = new BooleanConverter(Boolean.TRUE);
if (converter.convert(Boolean.class, some_Method_That_Changes_Status_And_Returns_Non_Boolean()) && some_Boolean_Method_That_Checks_The_Status())
{
//......
}
else if (converter.convert(Boolean.class, some_Other_Method_That_Changes_Status_And_Returns_Non_Boolean()) && some_Boolean_Method_That_Checks_The_Status())
{
//......
}
else
{
//......
}
Was it helpful?

Solution

Try:

Boolean b = converter.convert(Boolean.class, someMethodThatReturnsSomething());

The convert method is supported to return a T where T is specified by the Class provided as the first parameter (i.e. the return value's type depends in the first parameter's type).

It looks like the above should work if someMethodThatReturnsSomething() returns a String. If it doesn't, it's not so clear what should happen (it might be a runtime exception).

UPDATE:

Oh! Change:

Converter converter = new BooleanConverter(Boolean.TRUE);

To:

BooleanConverter converter = new BooleanConverter(Boolean.TRUE);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top