001package ca.uhn.fhir.util; 002 003/* 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2020 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 ca.uhn.fhir.context.ConfigurationException; 024import org.apache.commons.lang3.Validate; 025 026import java.lang.reflect.Constructor; 027import java.lang.reflect.Field; 028import java.lang.reflect.Method; 029import java.lang.reflect.Modifier; 030import java.lang.reflect.ParameterizedType; 031import java.lang.reflect.Type; 032import java.lang.reflect.TypeVariable; 033import java.lang.reflect.WildcardType; 034import java.util.ArrayList; 035import java.util.Comparator; 036import java.util.HashSet; 037import java.util.LinkedHashSet; 038import java.util.List; 039import java.util.concurrent.ConcurrentHashMap; 040 041public class ReflectionUtil { 042 043 public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; 044 public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0]; 045 private static final ConcurrentHashMap<String, Object> ourFhirServerVersions = new ConcurrentHashMap<>(); 046 private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ReflectionUtil.class); 047 048 /** 049 * Returns all methods declared against {@literal theClazz}. This method returns a predictable order, which is 050 * sorted by method name and then by parameters. 051 */ 052 public static List<Method> getDeclaredMethods(Class<?> theClazz) { 053 HashSet<Method> foundMethods = new LinkedHashSet<>(); 054 Method[] declaredMethods = theClazz.getDeclaredMethods(); 055 for (Method next : declaredMethods) { 056 try { 057 Method method = theClazz.getMethod(next.getName(), next.getParameterTypes()); 058 foundMethods.add(method); 059 } catch (NoSuchMethodException | SecurityException e) { 060 foundMethods.add(next); 061 } 062 } 063 064 List<Method> retVal = new ArrayList<>(foundMethods); 065 retVal.sort((Comparator.comparing(ReflectionUtil::describeMethodInSortFriendlyWay))); 066 return retVal; 067 } 068 069 /** 070 * Returns a description like <code>startsWith params(java.lang.String, int) returns(boolean)</code>. 071 * The format is chosen in order to provide a predictable and useful sorting order. 072 */ 073 public static String describeMethodInSortFriendlyWay(Method theMethod) { 074 StringBuilder b = new StringBuilder(); 075 b.append(theMethod.getName()); 076 b.append(" returns("); 077 b.append(theMethod.getReturnType().getName()); 078 b.append(") params("); 079 Class<?>[] parameterTypes = theMethod.getParameterTypes(); 080 for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { 081 if (i > 0) { 082 b.append(", "); 083 } 084 Class<?> next = parameterTypes[i]; 085 b.append(next.getName()); 086 } 087 b.append(")"); 088 return b.toString(); 089 } 090 091 public static Class<?> getGenericCollectionTypeOfField(Field next) { 092 ParameterizedType collectionType = (ParameterizedType) next.getGenericType(); 093 return getGenericCollectionTypeOf(collectionType.getActualTypeArguments()[0]); 094 } 095 096 /** 097 * For a field of type List<Enumeration<Foo>>, returns Foo 098 */ 099 public static Class<?> getGenericCollectionTypeOfFieldWithSecondOrderForList(Field next) { 100 if (!List.class.isAssignableFrom(next.getType())) { 101 return getGenericCollectionTypeOfField(next); 102 } 103 104 Class<?> type; 105 ParameterizedType collectionType = (ParameterizedType) next.getGenericType(); 106 Type firstArg = collectionType.getActualTypeArguments()[0]; 107 if (ParameterizedType.class.isAssignableFrom(firstArg.getClass())) { 108 ParameterizedType pt = ((ParameterizedType) firstArg); 109 Type pt2 = pt.getActualTypeArguments()[0]; 110 return (Class<?>) pt2; 111 } 112 type = (Class<?>) firstArg; 113 return type; 114 } 115 116 public static Class<?> getGenericCollectionTypeOfMethodParameter(Method theMethod, int theParamIndex) { 117 Type genericParameterType = theMethod.getGenericParameterTypes()[theParamIndex]; 118 if (Class.class.equals(genericParameterType) || Class.class.equals(genericParameterType.getClass())) { 119 return null; 120 } 121 ParameterizedType collectionType = (ParameterizedType) genericParameterType; 122 return getGenericCollectionTypeOf(collectionType.getActualTypeArguments()[0]); 123 } 124 125 public static Class<?> getGenericCollectionTypeOfMethodReturnType(Method theMethod) { 126 Type genericReturnType = theMethod.getGenericReturnType(); 127 if (!(genericReturnType instanceof ParameterizedType)) { 128 return null; 129 } 130 ParameterizedType collectionType = (ParameterizedType) genericReturnType; 131 return getGenericCollectionTypeOf(collectionType.getActualTypeArguments()[0]); 132 } 133 134 @SuppressWarnings({"rawtypes"}) 135 private static Class<?> getGenericCollectionTypeOf(Type theType) { 136 Class<?> type; 137 if (ParameterizedType.class.isAssignableFrom(theType.getClass())) { 138 ParameterizedType pt = ((ParameterizedType) theType); 139 type = (Class<?>) pt.getRawType(); 140 } else if (theType instanceof TypeVariable<?>) { 141 Type decl = ((TypeVariable) theType).getBounds()[0]; 142 return (Class<?>) decl; 143 } else if (theType instanceof WildcardType) { 144 Type decl = ((WildcardType) theType).getUpperBounds()[0]; 145 return (Class<?>) decl; 146 } else { 147 type = (Class<?>) theType; 148 } 149 return type; 150 } 151 152 public static boolean isInstantiable(Class<?> theType) { 153 return !theType.isInterface() && !Modifier.isAbstract(theType.getModifiers()); 154 } 155 156 /** 157 * Instantiate a class by no-arg constructor, throw {@link ConfigurationException} if we fail to do so 158 */ 159 public static <T> T newInstance(Class<T> theType) { 160 Validate.notNull(theType, "theType must not be null"); 161 try { 162 return theType.getConstructor().newInstance(); 163 } catch (Exception e) { 164 throw new ConfigurationException("Failed to instantiate " + theType.getName(), e); 165 } 166 } 167 168 public static <T> T newInstance(Class<T> theType, Class<?> theArgumentType, Object theArgument) { 169 Validate.notNull(theType, "theType must not be null"); 170 try { 171 Constructor<T> constructor = theType.getConstructor(theArgumentType); 172 return constructor.newInstance(theArgument); 173 } catch (Exception e) { 174 throw new ConfigurationException("Failed to instantiate " + theType.getName(), e); 175 } 176 } 177 178 public static Object newInstanceOfFhirServerType(String theType) { 179 String errorMessage = "Unable to instantiate server framework. Please make sure that hapi-fhir-server library is on your classpath!"; 180 String wantedType = "ca.uhn.fhir.rest.api.server.IFhirVersionServer"; 181 return newInstanceOfType(theType, theType, errorMessage, wantedType, new Class[0], new Object[0]); 182 } 183 184 private static Object newInstanceOfType(String theKey, String theType, String errorMessage, String wantedType, Class<?>[] theParameterArgTypes, Object[] theConstructorArgs) { 185 Object fhirServerVersion = ourFhirServerVersions.get(theKey); 186 if (fhirServerVersion == null) { 187 try { 188 Class<?> type = Class.forName(theType); 189 Class<?> serverType = Class.forName(wantedType); 190 Validate.isTrue(serverType.isAssignableFrom(type)); 191 fhirServerVersion = type.getConstructor(theParameterArgTypes).newInstance(theConstructorArgs); 192 } catch (Exception e) { 193 throw new ConfigurationException(errorMessage, e); 194 } 195 196 ourFhirServerVersions.put(theKey, fhirServerVersion); 197 } 198 return fhirServerVersion; 199 } 200 201 public static <T> T newInstanceOrReturnNull(String theClassName, Class<T> theType) { 202 return newInstanceOrReturnNull(theClassName, theType, EMPTY_CLASS_ARRAY, EMPTY_OBJECT_ARRAY); 203 } 204 205 @SuppressWarnings("unchecked") 206 public static <T> T newInstanceOrReturnNull(String theClassName, Class<T> theType, Class<?>[] theArgTypes, Object[] theArgs) { 207 try { 208 Class<?> clazz = Class.forName(theClassName); 209 if (!theType.isAssignableFrom(clazz)) { 210 throw new ConfigurationException(theClassName + " is not assignable to " + theType); 211 } 212 return (T) clazz.getConstructor(theArgTypes).newInstance(theArgs); 213 } catch (ConfigurationException e) { 214 throw e; 215 } catch (Exception e) { 216 ourLog.info("Failed to instantiate {}: {}", theClassName, e.toString()); 217 return null; 218 } 219 } 220 221 public static boolean typeExists(String theName) { 222 try { 223 Class.forName(theName); 224 return true; 225 } catch (ClassNotFoundException theE) { 226 return false; 227 } 228 } 229}