1 package com.lexicalscope.fluentreflection; 2 3 import static ch.lambdaj.Lambda.convert; 4 import static com.lexicalscope.fluentreflection.Visibility.visibilityFromModifiers; 5 6 import java.lang.reflect.Constructor; 7 import java.lang.reflect.InvocationTargetException; 8 import java.util.List; 9 10 import com.google.inject.TypeLiteral; 11 12 final class FluentConstructorImpl<T> extends AbstractFluentAnnotated implements FluentConstructor<T> { 13 private final ReflectedTypeFactory reflectedTypeFactory; 14 private final TypeLiteral<T> typeLiteral; 15 private final Constructor<T> constructor; 16 17 public FluentConstructorImpl( 18 final ReflectedTypeFactory reflectedTypeFactory, 19 final TypeLiteral<T> typeLiteral, 20 final Constructor<T> constructor) { 21 super(reflectedTypeFactory, constructor); 22 this.reflectedTypeFactory = reflectedTypeFactory; 23 this.typeLiteral = typeLiteral; 24 this.constructor = constructor; 25 } 26 27 @Override public int argCount() { 28 return constructor.getParameterTypes().length; 29 } 30 31 @Override public List<FluentClass<?>> args() { 32 return convert( 33 typeLiteral.getParameterTypes(constructor), 34 new ConvertTypeLiteralToReflectedType(reflectedTypeFactory)); 35 } 36 37 @Override public Constructor<T> member() { 38 return constructor; 39 } 40 41 @Override public T callRaw(final Object... args) { 42 try { 43 return constructor.newInstance(args); 44 } catch (final InstantiationException e) { 45 throw new InstantiationRuntimeException(e, constructor); 46 } catch (final IllegalAccessException e) { 47 throw new IllegalAccessRuntimeException(e, constructor); 48 } catch (final InvocationTargetException e) { 49 throw new InvocationTargetRuntimeException(e, constructor); 50 } 51 } 52 53 @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public FluentObject<?> call(final Object... args) { 54 final Object object = callRaw(args); 55 if(object == null) { 56 return null; 57 } 58 return reflectedTypeFactory.reflect((Class) object.getClass(), object); 59 } 60 61 @Override public FluentClass<?> declarer() { 62 return reflectedTypeFactory.reflect(typeLiteral); 63 } 64 65 @Override public String name() { 66 return constructor.getName(); 67 } 68 69 @Override public String property() { 70 return "<init>"; 71 } 72 73 @Override public FluentClass<?> type() { 74 return declarer(); 75 } 76 77 @Override public Visibility visibility() { 78 return visibilityFromModifiers(constructor.getModifiers()); 79 } 80 81 @Override public <S> FluentCall<S> as(final Class<S> returnType) { 82 return new AbstractCall<S>(reflectedTypeFactory) { 83 @Override public S callRaw(final Object... args) { 84 return returnType.cast(FluentConstructorImpl.this.callRaw(args)); 85 } 86 }; 87 } 88 89 @Override public boolean isStatic() { 90 return true; 91 } 92 93 @Override public boolean isFinal() { 94 return false; 95 } 96 }