source: java/main/src/main/java/com/framsticks/util/lang/Numbers.java @ 193

Last change on this file since 193 was 193, checked in by Maciej Komosinski, 10 years ago

Set svn:eol-style native for all textual files

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