001/*
002 * Copyright (C) 2012 Facebook, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may
005 * not use this file except in compliance with the License. You may obtain
006 * a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations
014 * under the License.
015 */
016package com.facebook.swift.codec.metadata;
017
018import javax.annotation.concurrent.Immutable;
019
020import java.lang.reflect.Field;
021
022import static com.google.common.base.Preconditions.checkArgument;
023import static com.google.common.base.Preconditions.checkNotNull;
024
025@Immutable
026public class ThriftFieldInjection implements ThriftInjection
027{
028    private final short id;
029    private final String name;
030    private final Field field;
031    private final FieldKind fieldKind;
032
033    public ThriftFieldInjection(short id, String name, Field field, FieldKind fieldKind)
034    {
035        this.name = checkNotNull(name, "name is null");
036        this.field = checkNotNull(field, "field is null");
037        this.fieldKind = checkNotNull(fieldKind, "fieldKind is null");
038
039        switch (fieldKind) {
040            case THRIFT_FIELD:
041                checkArgument(id >= 0, "fieldId is negative");
042                break;
043            case THRIFT_UNION_ID:
044                checkArgument (id == Short.MIN_VALUE, "fieldId must be Short.MIN_VALUE for thrift_union_id");
045                break;
046        }
047
048        this.id = id;
049    }
050
051    @Override
052    public FieldKind getFieldKind()
053    {
054        return fieldKind;
055    }
056
057    @Override
058    public short getId()
059    {
060        return id;
061    }
062
063    @Override
064    public String getName()
065    {
066        return name;
067    }
068
069    public Field getField()
070    {
071        return field;
072    }
073
074    @Override
075    public String toString()
076    {
077        final StringBuilder sb = new StringBuilder();
078        sb.append("ThriftFieldInjection");
079        sb.append("{fieldId=").append(id);
080        sb.append(", name=").append(name);
081        sb.append(", fieldKind=").append(fieldKind);
082        sb.append(", field=").append(field.getDeclaringClass().getSimpleName()).append(".").append(field.getName());
083        sb.append('}');
084        return sb.toString();
085    }
086}