John Jerrby
John Jerrby

Reputation: 1703

cast type error from long to decimal type object

I having the following code and member value is type object and in this process = long and i want to cast it to big decimal ,when i trying the following code i get error:java.lang.Double cannot be cast to [C

} else if  (typeName.equals("java.math.BigDecimal"))) {
        return new SwitchInputType<BigDecimal>(new BigDecimal((char[]) memberValue));

Upvotes: 0

Views: 474

Answers (4)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

The [C represents the type "array of char", and indeed, you can't cast a Double to an array of char, nor should you want to. According to the message, memberValue is a Double, so you just want to do

return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue));

Upvotes: 2

Jesper
Jesper

Reputation: 206816

The error message means that memberValue is a java.lang.Double object, and you are trying to cast it to char[]. That doesn't work, because a Double is not a char[].

In this case, you can just remove the cast, and call doubleValue() on the Double object:

return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue.doubleValue()));

This way, you're using the constructor of BigDecimal that takes a double instead of a char[].

If the type of memberValue is Object, you'll have to cast it to Double first:

((Double)memberValue).doubleValue()

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359816

The error message:

java.lang.Double cannot be cast to [C

tells you that this cast is illegal:

(char[]) memberValue

so don't do it. The error message tells you that memberValue is a Double, so this should work:

return new SwitchInputType<BigDecimal>(new BigDecimal((Double) memberValue));

Depending on the declared type of memberValue the cast may be completely unnecessary, though it sounds like the declared type is Object. Alternately, since there is a BigDecimal constructor which accepts strings, you could try to get away with this, though it's not really any less-smelly:

return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue.toString()));

Upvotes: 2

DigitalGhost
DigitalGhost

Reputation: 783

If you are getting that error, it means that memberValue is a Double. In this case, you should probably just use

new BigDecimal(memberValue)

but I'd have to see more code to be sure.

Upvotes: 0

Related Questions