source: java/main/src/main/java/com/framsticks/util/lang/FlagsUtil.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.5 KB
Line 
1package com.framsticks.util.lang;
2
3import java.lang.reflect.Field;
4import org.apache.logging.log4j.Logger;
5import org.apache.logging.log4j.LogManager;
6
7import com.framsticks.util.lang.Delimeted;
8
9public final class FlagsUtil {
10
11        private final static Logger log = LogManager.getLogger(FlagsUtil.class);
12
13        private FlagsUtil() {
14        }
15
16        public static String write(Class<?> flagsClass, int flags, String empty) {
17                Delimeted<String> d = new Delimeted<String>("+", empty);
18                try {
19                        for (Field f : flagsClass.getDeclaredFields()) {
20                                if (f.getType() != int.class) {
21                                        continue;
22                                }
23                                if ((flags & f.getInt(null)) != 0) {
24                                        d.append(f.getName());
25                                }
26                        }
27                } catch (IllegalArgumentException | IllegalAccessException e) {
28                        e.printStackTrace();
29                }
30                return d.build();
31        }
32
33        public static Integer read(Class<?> flagsClass, String flags) {
34                Integer allFlags = 0;
35                String[] flagsSplitted = flags.split("\\+");
36                for (String flag : flagsSplitted) {
37                        try {
38                                allFlags |= Integer.valueOf(flag);
39                        } catch (NumberFormatException ex) {
40                                try {
41                                        Field field = flagsClass.getDeclaredField(flag.toUpperCase());
42                                        allFlags |= Integer.parseInt(field.get(null).toString());
43                                } catch (SecurityException e) {
44                                        log.warn("security exception was thrown while trying to read flag ({})", flag);
45                                } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
46                                        log.warn("selected flag is not known ({})", flag);
47                                }
48                        }
49                }
50                return allFlags;
51        }
52}
Note: See TracBrowser for help on using the repository browser.