1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package com.gridsystems.nextgrid.api.pom.ref;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 public class ScalarReference<E> extends ReferenceSupport<E> {
36
37
38
39
40 private static final long serialVersionUID = -913366860389629686L;
41
42
43
44
45 private final Class<E> type;
46
47
48
49
50 private E value;
51
52
53
54
55
56
57 public ScalarReference(Class<E> type) {
58 this.type = type;
59
60 }
61
62
63
64
65
66
67
68 public ScalarReference(Class<E> type, E value) {
69 this(type);
70 setValue(value);
71 }
72
73
74
75
76 @SuppressWarnings("unchecked")
77 public final void setValue(Object value) {
78 LOG.debug("Setting value [" + this + " ::= " + value + "]");
79 this.value = (E)castTo(getValueType(), value);
80 setAvailable(value != null);
81 }
82
83
84
85
86 public final E getValue() {
87 return this.value;
88 }
89
90
91
92
93 public final Class<E> getValueType() {
94 return this.type;
95 }
96
97
98
99
100 public boolean canCastTo(Class<?> type) {
101 return type != null && (type.isAssignableFrom(String.class)
102 || type.isAssignableFrom(this.type));
103 }
104
105
106
107
108 public boolean canCastFrom(Class<?> type) {
109 return type != null && (this.type.isAssignableFrom(String.class)
110 || this.type.isAssignableFrom(type));
111 }
112
113
114
115
116 public Object castTo(Class<?> type) {
117 return castTo(type, this.value);
118 }
119
120
121
122
123
124
125
126
127 private Object castTo(Class<?> type, Object value) {
128 if (type.isAssignableFrom(String.class)) {
129 return (value == null) ? null : value.toString();
130 } else if (type.isAssignableFrom(this.type)) {
131 return value;
132 } else {
133 throw new ClassCastException("Cannot cast to " + type);
134 }
135 }
136
137 }