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
015package org.apache.tapestry5.internal.plastic;
016
017import org.apache.tapestry5.plastic.FieldHandle;
018
019public 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    @Override
041    public Object get(Object instance)
042    {
043        checkNullInstance(instance, "get");
044
045        return shim.get(instance, fieldIndex);
046    }
047
048    private void checkNullInstance(Object instance, String action)
049    {
050        if (instance == null)
051            throw new NullPointerException(String.format(
052                    "Unable to %s value of field %s of class %s, as provided instance is null.", action, fieldName,
053                    className));
054    }
055
056    @Override
057    public void set(Object instance, Object newValue)
058    {
059        checkNullInstance(instance, "set");
060
061        shim.set(instance, fieldIndex, newValue);
062    }
063}