001/*
002 * #%L
003 * HAPI FHIR - Core Library
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.context;
021
022import ca.uhn.fhir.i18n.Msg;
023import ca.uhn.fhir.model.api.annotation.Child;
024import ca.uhn.fhir.model.api.annotation.Description;
025import org.hl7.fhir.instance.model.api.IBase;
026
027import java.lang.reflect.Field;
028
029public class RuntimeChildPrimitiveEnumerationDatatypeDefinition extends RuntimeChildPrimitiveDatatypeDefinition {
030
031        private Object myBinder;
032        private Class<? extends Enum<?>> myEnumType;
033
034        public RuntimeChildPrimitiveEnumerationDatatypeDefinition(
035                        Field theField,
036                        String theElementName,
037                        Child theChildAnnotation,
038                        Description theDescriptionAnnotation,
039                        Class<? extends IBase> theDatatype,
040                        Class<? extends Enum<?>> theBinderType) {
041                super(theField, theElementName, theDescriptionAnnotation, theChildAnnotation, theDatatype);
042
043                myEnumType = theBinderType;
044        }
045
046        @Override
047        public Class<? extends Enum<?>> getBoundEnumType() {
048                return myEnumType;
049        }
050
051        @Override
052        public Object getInstanceConstructorArguments() {
053                Object retVal = myBinder;
054                if (retVal == null) {
055                        retVal = toEnumFactory(myEnumType);
056                        myBinder = retVal;
057                }
058                return retVal;
059        }
060
061        static Object toEnumFactory(Class<?> theEnumerationType) {
062                Class<?> clazz;
063                String className = theEnumerationType.getName() + "EnumFactory";
064                Object retVal;
065                try {
066                        clazz = Class.forName(className);
067                        retVal = clazz.newInstance();
068                } catch (Exception e) {
069                        throw new ConfigurationException(Msg.code(1694) + "Failed to instantiate " + className, e);
070                }
071                return retVal;
072        }
073}