001/*-------------------------------------------------------------------------+ 002| | 003| Copyright 2005-2011 the ConQAT Project | 004| | 005| Licensed under the Apache License, Version 2.0 (the "License"); | 006| you may not use this file except in compliance with the License. | 007| You may obtain a copy of the License at | 008| | 009| http://www.apache.org/licenses/LICENSE-2.0 | 010| | 011| Unless required by applicable law or agreed to in writing, software | 012| distributed under the License is distributed on an "AS IS" BASIS, | 013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 014| See the License for the specific language governing permissions and | 015| limitations under the License. | 016+-------------------------------------------------------------------------*/ 017package org.conqat.lib.commons.serialization.classes; 018 019import java.io.IOException; 020 021import org.conqat.lib.commons.serialization.SerializationConsistencyException; 022 023/** 024 * Base class for fields of primitive type. 025 */ 026public abstract class SerializedPrimitiveFieldBase extends SerializedFieldBase { 027 028 /** Constructor. */ 029 protected SerializedPrimitiveFieldBase(String name) { 030 super(name); 031 } 032 033 /** 034 * Ensures that the given value object is of the given type and not null. 035 * Returns the casted type. 036 */ 037 @SuppressWarnings("unchecked") 038 protected <T> T ensureType(Object value, Class<T> type) throws SerializationConsistencyException { 039 if (!type.isInstance(value)) { 040 String actualType = null; 041 if (value != null) { 042 actualType = value.getClass().getName(); 043 } 044 throw new SerializationConsistencyException( 045 "Would have expected type " + type + " for field " + getName() + " but was " + actualType); 046 } 047 return (T) value; 048 } 049 050 /** Factory method for creating a primitive field from its type code. */ 051 public static SerializedPrimitiveFieldBase fromTypeCode(char typeCode, String fieldName) throws IOException { 052 switch (typeCode) { 053 case SerializedByteField.TYPE_CODE: 054 return new SerializedByteField(fieldName); 055 case SerializedCharField.TYPE_CODE: 056 return new SerializedCharField(fieldName); 057 case SerializedDoubleField.TYPE_CODE: 058 return new SerializedDoubleField(fieldName); 059 case SerializedFloatField.TYPE_CODE: 060 return new SerializedFloatField(fieldName); 061 case SerializedIntField.TYPE_CODE: 062 return new SerializedIntField(fieldName); 063 case SerializedLongField.TYPE_CODE: 064 return new SerializedLongField(fieldName); 065 case SerializedShortField.TYPE_CODE: 066 return new SerializedShortField(fieldName); 067 case SerializedBooleanField.TYPE_CODE: 068 return new SerializedBooleanField(fieldName); 069 default: 070 throw new SerializationConsistencyException("Unrecognized type code: " + typeCode); 071 } 072 } 073}