1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.jexl3.internal.introspection;
19
20 import static java.lang.reflect.Modifier.isFinal;
21 import static java.lang.reflect.Modifier.isStatic;
22
23 import java.lang.reflect.Field;
24
25 import org.apache.commons.jexl3.introspection.JexlPropertyGet;
26
27 /**
28 * A JexlPropertyGet for public fields.
29 */
30 public final class FieldGetExecutor implements JexlPropertyGet {
31
32 /**
33 * Attempts to discover a FieldGetExecutor.
34 *
35 * @param is the introspector
36 * @param clazz the class to find the get method from
37 * @param identifier the key to use as an argument to the get method
38 * @return the executor if found, null otherwise
39 */
40 public static JexlPropertyGet discover(final Introspector is, final Class<?> clazz, final String identifier) {
41 if (identifier != null) {
42 final Field field = is.getField(clazz, identifier);
43 if (field != null) {
44 return new FieldGetExecutor(field);
45 }
46 }
47 return null;
48 }
49
50 /**
51 * The public field.
52 */
53 private final Field field;
54
55 /**
56 * Creates a new instance of FieldPropertyGet.
57 *
58 * @param theField the class public field
59 */
60 private FieldGetExecutor(final Field theField) {
61 field = theField;
62 }
63
64 @Override
65 public Object invoke(final Object obj) throws Exception {
66 return field.get(obj);
67 }
68
69 @Override
70 public boolean isCacheable() {
71 return true;
72 }
73
74 @Override
75 public boolean isConstant() {
76 if (field.isEnumConstant()) {
77 return true;
78 }
79 final int modifiers = field.getModifiers();
80 // public static final fields are (considered) constants
81 return isFinal(modifiers) && isStatic(modifiers);
82 }
83
84 @Override
85 public boolean tryFailed(final Object rval) {
86 return rval == Uberspect.TRY_FAILED;
87 }
88
89 @Override
90 public Object tryInvoke(final Object obj, final Object key) {
91 if (obj.getClass().equals(field.getDeclaringClass()) && key.equals(field.getName())) {
92 try {
93 return field.get(obj);
94 } catch (final IllegalAccessException xill) {
95 return Uberspect.TRY_FAILED;
96 }
97 }
98 return Uberspect.TRY_FAILED;
99 }
100
101 }