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