1 | package com.framsticks.params.types; |
---|
2 | |
---|
3 | import javax.annotation.concurrent.Immutable; |
---|
4 | |
---|
5 | import com.framsticks.params.CastFailure; |
---|
6 | import com.framsticks.params.ParamBuilder; |
---|
7 | import com.framsticks.params.PrimitiveParam; |
---|
8 | import com.framsticks.params.ReassignResult; |
---|
9 | import com.framsticks.util.lang.Numbers; |
---|
10 | |
---|
11 | /** |
---|
12 | * @author Piotr Sniegowski |
---|
13 | */ |
---|
14 | @Immutable |
---|
15 | public class BooleanParam extends PrimitiveParam<Boolean> { |
---|
16 | |
---|
17 | /** |
---|
18 | * @param builder |
---|
19 | */ |
---|
20 | public BooleanParam(ParamBuilder builder) { |
---|
21 | super(builder.fillDef(false).fillStorageType(Boolean.class)); |
---|
22 | } |
---|
23 | |
---|
24 | @Override |
---|
25 | public Class<?> getStorageType() { |
---|
26 | return Boolean.class; |
---|
27 | } |
---|
28 | |
---|
29 | @Override |
---|
30 | public ReassignResult<Boolean> reassign(Object newValue, Object oldValue) throws CastFailure { |
---|
31 | if (newValue instanceof Boolean) { |
---|
32 | return ReassignResult.create((Boolean) newValue); |
---|
33 | } |
---|
34 | if (newValue instanceof Integer) { |
---|
35 | return ReassignResult.create(((Integer) newValue) != 0); |
---|
36 | } |
---|
37 | if (newValue instanceof String) { |
---|
38 | if ("true".equals(newValue)) { |
---|
39 | return ReassignResult.create(true); |
---|
40 | } |
---|
41 | if ("false".equals(newValue)) { |
---|
42 | return ReassignResult.create(false); |
---|
43 | } |
---|
44 | Integer i = Numbers.cast(newValue, Integer.class); |
---|
45 | if (i != null) { |
---|
46 | return ReassignResult.create(i != 0); |
---|
47 | } |
---|
48 | throw new CastFailure(); |
---|
49 | } |
---|
50 | throw new CastFailure(); |
---|
51 | } |
---|
52 | |
---|
53 | @Override |
---|
54 | public String getFramsTypeName() { |
---|
55 | return "d 0 1"; |
---|
56 | } |
---|
57 | |
---|
58 | @Override |
---|
59 | public String serialize(Object value) { |
---|
60 | assert value instanceof Boolean; |
---|
61 | return ((Boolean)value) ? "1" : "0"; |
---|
62 | } |
---|
63 | } |
---|