001// Copyright 2023 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.tapestry5.plastic; 016 017/** 018 * <p> 019 * Interface that can be implemented to provide access to field values based on their name. 020 * Usually implemented with {@linkplain PlasticUtils#implementFieldValueProvider(PlasticClass, java.util.Set)}, 021 * which doesn't use reflection. 022 * </p> 023 * <p> 024 * The name of its abstract method is intended to avoid clashes with other existing methods 025 * in the class. 026 * </p> 027 * @see PlasticUtils#implementFieldValueProvider(PlasticClass, java.util.Set) 028 * @since 5.8.4 029 */ 030public interface FieldValueProvider 031{ 032 /** 033 * Returns the value of a given field. 034 * @param fieldName the field name. 035 * @return the field value. 036 */ 037 Object __fieldValueProvider__get(String fieldName); 038 039 /** 040 * <p> 041 * Returns the value of a given field in a given object if it belongs to a class 042 * that implements {@linkplain FieldValueProvider}. Otherwise, it throws an exception. 043 * </p> 044 * <p> 045 * This is an utility method to avoid having to make casts very time you need to call 046 * {@linkplain #__fieldValueProvider__get(String)}. 047 * </p> 048 * @param object an object. 049 * @param fieldName the field name. 050 * @return the field value. 051 */ 052 static Object get(Object object, String fieldName) 053 { 054 if (object instanceof FieldValueProvider) 055 { 056 return ((FieldValueProvider) object).__fieldValueProvider__get(fieldName); 057 } 058 else 059 { 060 throw new RuntimeException("Class " + object.getClass().getName() + " doesn't implement " + FieldValueProvider.class.getSimpleName()); 061 } 062 } 063 064}