/v2/trunk/src/main/java/net/usikkert/kouchat/reflect/GenericArgumentExtractorImpl.java

http://kouchat.googlecode.com/ · Java · 71 lines · 31 code · 15 blank · 25 comment · 6 complexity · 2f5b2099910d2d11f1173335846b4f9a MD5 · raw file

  1. /***************************************************************************
  2. * Copyright 2006-2010 by Christian Ihle *
  3. * kontakt@usikkert.net *
  4. * *
  5. * This file is part of KouChat. *
  6. * *
  7. * KouInject is free software; you can redistribute it and/or modify *
  8. * it under the terms of the GNU Lesser General Public License as *
  9. * published by the Free Software Foundation, either version 3 of *
  10. * the License, or (at your option) any later version. *
  11. * *
  12. * KouInject is distributed in the hope that it will be useful, *
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of *
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
  15. * Lesser General Public License for more details. *
  16. * *
  17. * You should have received a copy of the GNU Lesser General Public *
  18. * License along with KouInject. *
  19. * If not, see <http://www.gnu.org/licenses/>. *
  20. ***************************************************************************/
  21. package net.usikkert.kouchat.reflect;
  22. import java.lang.reflect.ParameterizedType;
  23. import java.lang.reflect.Type;
  24. import javax.inject.Singleton;
  25. import net.usikkert.kouinject.annotation.Component;
  26. import org.apache.commons.lang.Validate;
  27. /**
  28. * TODO
  29. *
  30. * @author Christian Ihle
  31. */
  32. @Component
  33. @Singleton
  34. public class GenericArgumentExtractorImpl implements GenericArgumentExtractor {
  35. public Class<?> getGenericArgument(final Object objectWithGenericArgument, final Class<?> genericType) {
  36. Validate.notNull(objectWithGenericArgument, "Object can not be null");
  37. Validate.notNull(genericType, "Generic Type can not be null");
  38. final Type[] genericInterfaces = objectWithGenericArgument.getClass().getGenericInterfaces();
  39. for (final Type type : genericInterfaces) {
  40. if (type.equals(genericType)) {
  41. throw new UnsupportedOperationException("A generic argument must be present on " + genericType);
  42. }
  43. if (type instanceof ParameterizedType) {
  44. final ParameterizedType parameterizedType = (ParameterizedType) type;
  45. if (parameterizedType.getRawType().equals(genericType)) {
  46. final Type[] typeArguments = parameterizedType.getActualTypeArguments();
  47. if (typeArguments.length != 1) {
  48. throw new UnsupportedOperationException("Only one generic argument can be present on " + genericType);
  49. }
  50. return (Class<?>) typeArguments[0];
  51. }
  52. }
  53. }
  54. throw new IllegalArgumentException("The generic type " + genericType + " was not present on " + objectWithGenericArgument.getClass());
  55. }
  56. }