Line | |
---|
1 | package com.framsticks.util; |
---|
2 | |
---|
3 | import java.lang.reflect.InvocationTargetException; |
---|
4 | |
---|
5 | /** |
---|
6 | * @author Piotr Sniegowski |
---|
7 | */ |
---|
8 | public abstract class Numbers { |
---|
9 | public static <T extends Number> T parse(String value, Class<T> type) { |
---|
10 | if (!Strings.notEmpty(value)) { |
---|
11 | return null; |
---|
12 | } |
---|
13 | try { |
---|
14 | return (T)type.getMethod("valueOf", String.class).invoke(null, value); |
---|
15 | } catch (IllegalAccessException e) { |
---|
16 | e.printStackTrace(); |
---|
17 | } catch (InvocationTargetException e) { |
---|
18 | if (e.getTargetException() instanceof NumberFormatException) { |
---|
19 | return null; |
---|
20 | } |
---|
21 | e.printStackTrace(); |
---|
22 | } catch (NoSuchMethodException e) { |
---|
23 | e.printStackTrace(); |
---|
24 | } catch (NumberFormatException ignored) { |
---|
25 | return null; |
---|
26 | } |
---|
27 | return null; |
---|
28 | } |
---|
29 | |
---|
30 | |
---|
31 | public static <T extends Number> T cast(Object value, Class<T> type) { |
---|
32 | if (value == null) { |
---|
33 | return null; |
---|
34 | } |
---|
35 | if (value instanceof String) { |
---|
36 | return parse((String)value, type); |
---|
37 | } |
---|
38 | if (value.getClass() == type) { |
---|
39 | return type.cast(value); |
---|
40 | } |
---|
41 | return null; |
---|
42 | } |
---|
43 | |
---|
44 | } |
---|
Note: See
TracBrowser
for help on using the repository browser.