org.bbottema.javareflection.valueconverter.converters.CharacterConverters Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-reflection Show documentation
Show all versions of java-reflection Show documentation
Java Reflection provides a small package with nifty reflection features that will help with finding constructors, methods and value conversions
package org.bbottema.javareflection.valueconverter.converters;
import lombok.experimental.UtilityClass;
import org.bbottema.javareflection.util.Function;
import org.bbottema.javareflection.util.Function.Functions;
import org.bbottema.javareflection.valueconverter.ValueFunction;
import org.bbottema.javareflection.valueconverter.ValueFunction.ValueFunctionImpl;
import java.util.ArrayList;
import java.util.Collection;
/**
* Attempts to convert a Character
to the target datatype.
*
* Conversions are as follows:
*
* - String:
value.toString()
* - Character (or primitive character):
value
* - Number (or primitive number): Deferred to ({@link Character#getNumericValue(char)}) or cast to {@code int} if not in number
* 0-9 range.
* - Boolean (or boolean):
!value.equals('0')
*
*/
@UtilityClass
public final class CharacterConverters {
public static final Collection> CHARACTER_CONVERTERS = produceCharacterConverters();
private static Collection> produceCharacterConverters() {
ArrayList> converters = new ArrayList<>();
converters.add(new ValueFunctionImpl<>(char.class, Character.class, Functions.identity()));
converters.add(new ValueFunctionImpl<>(Character.class, char.class, Functions.identity()));
converters.add(new ValueFunctionImpl<>(char.class, char.class, Functions.identity()));
converters.add(new ValueFunctionImpl<>(Character.class, Character.class, Functions.identity()));
converters.add(new ValueFunctionImpl<>(Character.class, String.class, Functions.simpleToString()));
converters.add(new ValueFunctionImpl<>(Character.class, Number.class, new CharacterToNumberFunction()));
converters.add(new ValueFunctionImpl<>(Character.class, Boolean.class, new CharacterToBooleanFunction()));
return converters;
}
private static class CharacterToNumberFunction implements Function {
@Override
public Number apply(Character value) {
int numericValue = Character.getNumericValue(value);
return numericValue == -1 || numericValue > 9
? (int) value
: numericValue;
}
}
private static class CharacterToBooleanFunction implements Function {
@Override
public Boolean apply(Character value) {
return !value.equals('0');
}
}
}