consulting.omnia.util.cast.number.NumberCast Maven / Gradle / Ivy
package consulting.omnia.util.cast.number;
import java.math.BigDecimal;
import java.util.Date;
import consulting.omnia.util.cast.visitor.AbstractCastMainDataVisitor;
/**
* Casts data asNumber and Number asType.
*
* @author Ronaldo Blanc ronaldoblanc at omnia.consulting
* @since Sep 19, 2015
* @version 1.2.0
*/
public class NumberCast {
private static final NumberCastMainDataVisitor NUMBER_CAST_VISITOR = new NumberCast.NumberCastMainDataVisitor();
/**
* @param value Data to cast
* @param type Type to cast to
* @param Type to cast to
* @return Number of type R
*/
public static R asNumber(final Object value, final Class type) {
return NUMBER_CAST_VISITOR.asNumber(value, type);
}
/**
* @param value Number to cast
* @param type Type to cast to
* @param Type to cast to
* @return
*/
public static R asType(final Number value, final Class type) {
return NUMBER_CAST_VISITOR.asType(value, type);
}
/**
* Visitor like implementation of a numeric cast tool.
* @author Ronaldo Blanc ronaldoblanc at omnia.consulting
* @since Sep 19, 2015
* @version 1.0.0
*/
private static class NumberCastMainDataVisitor extends AbstractCastMainDataVisitor {
private BigDecimal number;
private Object result;
public R asNumber(final Object value, final Class type) {
accept(value);
return NumberBigDecimalCast.bigDecimalToNumber(number, type);
}
public R asType(final Number value, final Class type) {
result = value;
accept(type);
return castAs(result, type);
}
@Override
public void visit(final Character value) {
number = new BigDecimal(castAs(value, Character.class).toString());
}
@Override
public void visit(final String value) {
number = new BigDecimal(castAs(value, String.class));
}
@Override
public void visit(final Date value) {
number = NumberBigDecimalCast.numberToBigDecimal(castAs(value,
Date.class).getTime());
}
@Override
public void visit(final Boolean value) {
number = castAs(value, Boolean.class) == Boolean.TRUE ? BigDecimal.ONE
: BigDecimal.ZERO;
}
@Override
public void visit(final Number value) {
number = NumberBigDecimalCast.numberToBigDecimal(castAs(value,
Number.class));
}
@Override
public void visit(Class> type) {
if (String.class.isAssignableFrom(type)) {
result = String.valueOf(result);
}
if (Date.class.isAssignableFrom(type)) {
result = new Date(castAs(result, Number.class).longValue());
}
if (Boolean.class.isAssignableFrom(type)) {
result = (castAs(result, Number.class).byteValue() == 1);
}
if (Number.class.isAssignableFrom(type)) {
result = NumberBigDecimalCast.numberToBigDecimal(castAs(result,Number.class));
result = asNumber(result, type);
}
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy