|
| 1 | +package cucumber.runtime; |
| 2 | + |
| 3 | +import java.lang.reflect.InvocationTargetException; |
| 4 | +import java.util.Collection; |
| 5 | +import java.util.HashSet; |
| 6 | + |
| 7 | +public class Reflections { |
| 8 | + private final ClassFinder classFinder; |
| 9 | + |
| 10 | + public Reflections(ClassFinder classFinder) { |
| 11 | + this.classFinder = classFinder; |
| 12 | + } |
| 13 | + |
| 14 | + public <T> T instantiateExactlyOneSubclass(Class<T> parentType, String packageName, Class[] constructorParams, Object[] constructorArgs) { |
| 15 | + Collection<? extends T> instances = instantiateSubclasses(parentType, packageName, constructorParams, constructorArgs); |
| 16 | + if (instances.size() == 1) { |
| 17 | + return instances.iterator().next(); |
| 18 | + } else if (instances.size() == 0) { |
| 19 | + throw new CucumberException("Couldn't find a single implementation of " + parentType); |
| 20 | + } else { |
| 21 | + throw new CucumberException("Expected only one instance, but found too many: " + instances); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public <T> Collection<? extends T> instantiateSubclasses(Class<T> parentType, String packageName, Class[] constructorParams, Object[] constructorArgs) { |
| 26 | + Collection<T> result = new HashSet<T>(); |
| 27 | + for (Class<? extends T> clazz : classFinder.getDescendants(parentType, packageName)) { |
| 28 | + if (Utils.isInstantiable(clazz) && hasConstructor(clazz, constructorParams)) { |
| 29 | + result.add(newInstance(constructorParams, constructorArgs, clazz)); |
| 30 | + } |
| 31 | + } |
| 32 | + return result; |
| 33 | + } |
| 34 | + |
| 35 | + public <T> T newInstance(Class[] constructorParams, Object[] constructorArgs, Class<? extends T> clazz) { |
| 36 | + try { |
| 37 | + return clazz.getConstructor(constructorParams).newInstance(constructorArgs); |
| 38 | + } catch (InstantiationException e) { |
| 39 | + throw new CucumberException(e); |
| 40 | + } catch (IllegalAccessException e) { |
| 41 | + throw new CucumberException(e); |
| 42 | + } catch (InvocationTargetException e) { |
| 43 | + throw new CucumberException(e); |
| 44 | + } catch (NoSuchMethodException e) { |
| 45 | + throw new CucumberException(e); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + private boolean hasConstructor(Class<?> clazz, Class[] paramTypes) { |
| 50 | + try { |
| 51 | + clazz.getConstructor(paramTypes); |
| 52 | + return true; |
| 53 | + } catch (NoSuchMethodException e) { |
| 54 | + return false; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | +} |
0 commit comments