You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SimpleInjector.java 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.util;
  23. import java.lang.reflect.Constructor;
  24. import java.util.HashMap;
  25. import java.util.Map;
  26. /**
  27. * Facilitates simple injection of parameters into a constructor.
  28. * <p>
  29. * Injectors may be given a set of parent injectors, from which they will
  30. * inherit parameters. No checking is performed to prevent circular references
  31. * within parents.
  32. */
  33. public class SimpleInjector {
  34. /** The parent injectors, if any. */
  35. private final SimpleInjector[] parents;
  36. /** A mapping of known classes to the objects that should be injected. */
  37. private final Map<Class<?>, Object> parameters = new HashMap<>();
  38. /**
  39. * Creates a new injector which will inherit injection parameters from
  40. * the specified parent. Parent graphs must be acyclic.
  41. *
  42. * @param parents The injectors to inherit parameters from.
  43. */
  44. public SimpleInjector(final SimpleInjector ... parents) {
  45. this.parents = new SimpleInjector[parents.length];
  46. System.arraycopy(parents, 0, this.parents, 0, parents.length);
  47. }
  48. /**
  49. * Adds a new injectable object to this injector. If a constructor requires
  50. * an instance of the specified class, it will be given the specified
  51. * object. If an association has already been made for the specified class,
  52. * it will be replaced with the new object.
  53. *
  54. * @param clazz The type of parameter which should be injected
  55. * @param object The value to inject for the parameter
  56. */
  57. public void addParameter(final Class<?> clazz, final Object object) {
  58. parameters.put(clazz, object);
  59. }
  60. /**
  61. * Adds the specified object as an injectable parameter for all of its
  62. * known classes and interface. This is equivalent to calling
  63. * {@link #addParameter(Class, Object)} for the object's
  64. * class, all superclasses, and all interfaces.
  65. *
  66. * @param object The object to be injected
  67. */
  68. public void addParameter(final Object object) {
  69. // Iterate the object hierarchy up
  70. Class<?> target = object.getClass();
  71. do {
  72. addParameter(target, object);
  73. // Add all interfaces
  74. for (Class<?> iface : target.getInterfaces()) {
  75. addParameter(iface, object);
  76. }
  77. target = target.getSuperclass();
  78. } while (target != null);
  79. }
  80. /**
  81. * Retrieves a mapping of known injectable types to their corresponding
  82. * values. This mapping will also include mappings defined in all of this
  83. * injector's parents.
  84. *
  85. * @return A map of injectable parameters
  86. */
  87. public Map<Class<?>, Object> getParameters() {
  88. final Map<Class<?>, Object> localParams = new HashMap<>(parameters.size());
  89. for (SimpleInjector parent : parents) {
  90. localParams.putAll(parent.getParameters());
  91. }
  92. // Note: insert local parameters after so they override parent params.
  93. localParams.putAll(parameters);
  94. return localParams;
  95. }
  96. /**
  97. * Attempts to create a new instance of the specified class by injecting
  98. * parameters into the constructor(s). If no constructors are found which
  99. * can be satisfied by the known parameters, or if all satisfiable
  100. * constructors throw exceptions, an IllegalArgumentException will be
  101. * thrown.
  102. * <p>
  103. * If multiple constructors are available that are satisfiable using the
  104. * known arguments, no guarantee is given as to which will be used.
  105. *
  106. * @param <T> The type of object being instantiated
  107. * @param clazz The class to create an instance of
  108. * @return An instance of the specified class
  109. * @throws IllegalArgumentException If the class could not be instantiated
  110. */
  111. @SuppressWarnings("unchecked")
  112. public <T> T createInstance(final Class<T> clazz) {
  113. final Map<Class<?>, Object> params = getParameters();
  114. Throwable throwable = null;
  115. for (Constructor<?> rawCtor : clazz.getConstructors()) {
  116. final Constructor<T> ctor = (Constructor<T>) rawCtor;
  117. final Object[] args = new Object[ctor.getParameterTypes().length];
  118. int i = 0;
  119. for (Class<?> paramType : ctor.getParameterTypes()) {
  120. if (params.containsKey(paramType)) {
  121. args[i++] = params.get(paramType);
  122. } else {
  123. break;
  124. }
  125. }
  126. if (i == args.length) {
  127. try {
  128. return ctor.newInstance(args);
  129. } catch (ReflectiveOperationException ex) {
  130. throwable = ex;
  131. }
  132. }
  133. }
  134. if (throwable == null) {
  135. throw new IllegalArgumentException("No declared constructors "
  136. + "could be satisfied with known parameters");
  137. }
  138. throw new IllegalArgumentException("A satisfiable constructor was "
  139. + "found but threw an exception", throwable);
  140. }
  141. }