1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package ca.uhn.hl7v2.testpanel.util;
27
28 import java.lang.reflect.InvocationTargetException;
29
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class ClassUtils {
34
35 private static final Logger ourLog = LoggerFactory.getLogger(ClassUtils.class);
36
37 public static <T> T instantiateOrReturnNull(Class<? extends T> theClass) {
38 try {
39 return theClass.getConstructor().newInstance();
40 } catch (IllegalArgumentException e) {
41 ourLog.warn("Could not instantiate {}: {}", theClass.getName(), e.getMessage());
42 return null;
43 } catch (SecurityException e) {
44 ourLog.warn("Could not instantiate {}: {}", theClass.getName(), e.getMessage());
45 return null;
46 } catch (InstantiationException e) {
47 ourLog.warn("Could not instantiate {}: {}", theClass.getName(), e.getMessage());
48 return null;
49 } catch (IllegalAccessException e) {
50 ourLog.warn("Could not instantiate {}: {}", theClass.getName(), e.getMessage());
51 return null;
52 } catch (InvocationTargetException e) {
53 ourLog.warn("Could not instantiate {}: {}", theClass.getName(), e.getMessage());
54 return null;
55 } catch (NoSuchMethodException e) {
56 ourLog.warn("Could not instantiate {}: {}", theClass.getName(), e.getMessage());
57 return null;
58 }
59 }
60
61 public static <T> T instantiateOrReturnNull(String theClassName, Class<? extends T> theSuperclass) {
62 try {
63
64 @SuppressWarnings("unchecked")
65 Class<? extends T> clazz = (Class<? extends T>) Class.forName(theClassName);
66
67 if (!theSuperclass.isAssignableFrom(clazz)) {
68 ourLog.warn("Could not instantiate {}: {}", theClassName, "Not a subclass of " + theSuperclass.getName());
69 return null;
70 }
71
72 return instantiateOrReturnNull(clazz);
73
74 } catch (ClassNotFoundException e) {
75 return null;
76 }
77 }
78
79
80 }