001package ca.uhn.fhir.util.reflection;
002
003import java.lang.reflect.Method;
004
005import org.apache.commons.lang3.text.WordUtils;
006
007import ca.uhn.fhir.context.ConfigurationException;
008
009/*
010 * #%L
011 * HAPI FHIR - Core Library
012 * %%
013 * Copyright (C) 2014 - 2016 University Health Network
014 * %%
015 * Licensed under the Apache License, Version 2.0 (the "License");
016 * you may not use this file except in compliance with the License.
017 * You may obtain a copy of the License at
018 * 
019 *      http://www.apache.org/licenses/LICENSE-2.0
020 * 
021 * Unless required by applicable law or agreed to in writing, software
022 * distributed under the License is distributed on an "AS IS" BASIS,
023 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
024 * See the License for the specific language governing permissions and
025 * limitations under the License.
026 * #L%
027 */
028
029public class JavaReflectBeanUtil implements IBeanUtils {
030
031        @Override
032        public Method findAccessor(Class<?> theClassToIntrospect, Class<?> theTargetReturnType, String thePropertyName)
033                        throws NoSuchFieldException {
034                String methodName = "get" + WordUtils.capitalize(thePropertyName);
035                try {
036                        Method method = theClassToIntrospect.getMethod(methodName);
037                        if (theTargetReturnType.isAssignableFrom(method.getReturnType())) {
038                                return method;
039                        }
040                } catch (NoSuchMethodException e) {
041                        // fall through
042                } catch (SecurityException e) {
043                        throw new ConfigurationException("Failed to scan class '" + theClassToIntrospect + "' because of a security exception", e);
044                }
045                throw new NoSuchFieldException(theClassToIntrospect + " has no accessor for field " + thePropertyName);
046        }
047
048        @Override
049        public Method findMutator(Class<?> theClassToIntrospect, Class<?> theTargetArgumentType, String thePropertyName)
050                        throws NoSuchFieldException {
051                String methodName = "set" + WordUtils.capitalize(thePropertyName);
052                try {
053                        return theClassToIntrospect.getMethod(methodName, theTargetArgumentType);
054                } catch (NoSuchMethodException e) {
055                        //fall through
056                } catch (SecurityException e) {
057                        throw new ConfigurationException("Failed to scan class '" + theClassToIntrospect + "' because of a security exception", e);
058                }
059                throw new NoSuchFieldException(theClassToIntrospect + " has an mutator for field " + thePropertyName + " but it does not return type " + theTargetArgumentType);
060                
061        }
062
063}