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#implementPropertyValueProvider(PlasticClass, java.util.Set)}.
021 * </p>
022 * <p>
023 * The name of its abstract method is intended to avoid clashes with other existing methods
024 * in the class.
025 * </p>
026 * @see PlasticUtils#implementPropertyValueProvider(PlasticClass, java.util.Set)
027 * @since 5.8.4
028 */
029public interface PropertyValueProvider
030{
031    /**
032     * Returns the value of a given field.
033     * @param fieldName the field name.
034     * @return the field value.
035     */
036    Object __propertyValueProvider__get(String fieldName);
037    
038    /**
039     * <p>
040     * Returns the value of a given field in a given object if it belongs to a class
041     * that implements {@linkplain PropertyValueProvider}. Otherwise, it throws an exception.
042     * </p>
043     * <p>
044     * This is an utility method to avoid having to make casts very time you need to call
045     * {@linkplain #__propertyValueProvider__get(String)}.
046     * </p>
047     * @param object an object.
048     * @param fieldName the field name.
049     * @return the field value.
050     */
051    static Object get(Object object, String fieldName)
052    {
053        if (object instanceof PropertyValueProvider)
054        {
055            return ((PropertyValueProvider) object).__propertyValueProvider__get(fieldName);
056        }
057        else
058        {
059            throw new RuntimeException("Class " + object.getClass().getName() + " doesn't implement " + PropertyValueProvider.class.getSimpleName());
060        }
061    }
062    
063}