001    // Copyright 2011 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    
015    package org.apache.tapestry5.internal.plastic;
016    
017    import org.apache.tapestry5.plastic.FieldHandle;
018    
019    public class FieldHandleImpl implements FieldHandle
020    {
021        private final String className, fieldName;
022    
023        private final int fieldIndex;
024    
025        protected volatile PlasticClassHandleShim shim;
026    
027        public FieldHandleImpl(String className, String fieldName, int fieldIndex)
028        {
029            this.className = className;
030            this.fieldName = fieldName;
031            this.fieldIndex = fieldIndex;
032        }
033    
034        @Override
035        public String toString()
036        {
037            return String.format("FieldHandle[%s#%s]", className, fieldName);
038        }
039    
040        public Object get(Object instance)
041        {
042            checkNullInstance(instance, "get");
043    
044            return shim.get(instance, fieldIndex);
045        }
046    
047        private void checkNullInstance(Object instance, String action)
048        {
049            if (instance == null)
050                throw new NullPointerException(String.format(
051                        "Unable to %s value of field %s of class %s, as provided instance is null.", action, fieldName,
052                        className));
053        }
054    
055        public void set(Object instance, Object newValue)
056        {
057            checkNullInstance(instance, "set");
058    
059            shim.set(instance, fieldIndex, newValue);
060        }
061    }