15
15
package com .google .api .client .util ;
16
16
17
17
import java .lang .reflect .Field ;
18
+ import java .lang .reflect .InvocationTargetException ;
19
+ import java .lang .reflect .Method ;
18
20
import java .lang .reflect .Modifier ;
19
21
import java .lang .reflect .Type ;
22
+ import java .util .ArrayList ;
23
+ import java .util .List ;
20
24
import java .util .Map ;
21
25
import java .util .WeakHashMap ;
22
26
@@ -112,6 +116,9 @@ public static FieldInfo of(Field field) {
112
116
/** Field. */
113
117
private final Field field ;
114
118
119
+ /** Setters Method for field */
120
+ private final Method []setters ;
121
+
115
122
/**
116
123
* Data key name associated with the field for a non-enum-constant with a {@link Key} annotation,
117
124
* or data key value associated with the enum constant with a {@link Value} annotation or {@code
@@ -127,6 +134,21 @@ public static FieldInfo of(Field field) {
127
134
this .field = field ;
128
135
this .name = name == null ? null : name .intern ();
129
136
isPrimitive = Data .isPrimitive (getType ());
137
+ this .setters = settersMethodForField (field );
138
+ }
139
+
140
+ /**
141
+ * Creates list of setter methods for a field only in declaring class.
142
+ */
143
+ private Method [] settersMethodForField (Field field ) {
144
+ List <Method > methods = new ArrayList <Method >();
145
+ for (Method method : field .getDeclaringClass ().getDeclaredMethods ()) {
146
+ if (method .getName ().toLowerCase ().equals ("set" + field .getName ().toLowerCase ())
147
+ && method .getParameterTypes ().length == 1 ) {
148
+ methods .add (method );
149
+ }
150
+ }
151
+ return methods .toArray (new Method [methods .size ()]);
130
152
}
131
153
132
154
/**
@@ -203,6 +225,20 @@ public Object getValue(Object obj) {
203
225
* If the field is final, it checks that value being set is identical to the existing value.
204
226
*/
205
227
public void setValue (Object obj , Object value ) {
228
+ if (setters .length > 0 ) {
229
+ for (Method method : setters ) {
230
+ if (value == null || method .getParameterTypes ()[0 ].isAssignableFrom (value .getClass ())) {
231
+ try {
232
+ method .invoke (obj , value );
233
+ return ;
234
+ } catch (IllegalAccessException e ) {
235
+ // try to set field directly
236
+ } catch (InvocationTargetException e ) {
237
+ // try to set field directly
238
+ }
239
+ }
240
+ }
241
+ }
206
242
setFieldValue (field , obj , value );
207
243
}
208
244
0 commit comments