1
2
3
4
5
6 package mockit.internal.util;
7
8 import static mockit.internal.util.AutoBoxing.isWrapperOfPrimitiveType;
9
10 import edu.umd.cs.findbugs.annotations.NonNull;
11 import edu.umd.cs.findbugs.annotations.Nullable;
12
13 import java.math.BigDecimal;
14 import java.math.BigInteger;
15 import java.util.concurrent.atomic.AtomicInteger;
16 import java.util.concurrent.atomic.AtomicLong;
17
18 public final class TypeConversion {
19 private TypeConversion() {
20 }
21
22 @Nullable
23 public static Object convertFromString(@NonNull Class<?> targetType, @NonNull String value) {
24 if (targetType == String.class) {
25 return value;
26 }
27 if (isCharacter(targetType)) {
28 return value.charAt(0);
29 }
30 if (targetType.isPrimitive() || isWrapperOfPrimitiveType(targetType)) {
31 return newWrapperInstance(targetType, value);
32 }
33 if (targetType == BigDecimal.class) {
34 return new BigDecimal(value.trim());
35 }
36 if (targetType == BigInteger.class) {
37 return new BigInteger(value.trim());
38 }
39 if (targetType == AtomicInteger.class) {
40 return new AtomicInteger(Integer.parseInt(value.trim()));
41 }
42 if (targetType == AtomicLong.class) {
43 return new AtomicLong(Long.parseLong(value.trim()));
44 }
45 if (targetType.isEnum()) {
46
47 return enumValue(targetType, value);
48 }
49
50 return null;
51 }
52
53 private static boolean isCharacter(@NonNull Class<?> targetType) {
54 return targetType == char.class || targetType == Character.class;
55 }
56
57 @NonNull
58 private static Object newWrapperInstance(@NonNull Class<?> targetType, @NonNull String value) {
59 String trimmedValue = value.trim();
60
61 try {
62 if (targetType == int.class || targetType == Integer.class) {
63 return Integer.valueOf(trimmedValue);
64 }
65 if (targetType == long.class || targetType == Long.class) {
66 return Long.valueOf(trimmedValue);
67 }
68 if (targetType == short.class || targetType == Short.class) {
69 return Short.valueOf(trimmedValue);
70 }
71 if (targetType == byte.class || targetType == Byte.class) {
72 return Byte.valueOf(trimmedValue);
73 }
74 if (targetType == double.class || targetType == Double.class) {
75 return Double.valueOf(trimmedValue);
76 }
77 if (targetType == float.class || targetType == Float.class) {
78 return Float.valueOf(trimmedValue);
79 }
80 } catch (NumberFormatException e) {
81 throw new IllegalArgumentException("Invalid value \"" + trimmedValue + "\" for " + targetType);
82 }
83
84 return Boolean.valueOf(trimmedValue);
85 }
86
87 @NonNull
88 private static <E extends Enum<E>> Object enumValue(Class<?> targetType, @NonNull String value) {
89 @SuppressWarnings("unchecked")
90 Class<E> enumType = (Class<E>) targetType;
91 return Enum.valueOf(enumType, value);
92 }
93 }