private ConstructorModel newConstructorModel( Class fragmentClass, Constructor realConstructor, Constructor injectedConstructor) { int idx = 0; InjectedParametersModel parameters = new InjectedParametersModel(); Annotation[][] parameterAnnotations = injectedConstructor.getParameterAnnotations(); for (Type type : injectedConstructor.getGenericParameterTypes()) { final Annotation injectionAnnotation = first( filter( Annotations.hasAnnotation(InjectionScope.class), iterable(parameterAnnotations[idx]))); if (injectionAnnotation == null) { return null; // invalid constructor parameter } boolean optional = DependencyModel.isOptional(injectionAnnotation, parameterAnnotations[idx]); DependencyModel dependencyModel = new DependencyModel( injectionAnnotation, type, fragmentClass, optional, parameterAnnotations[idx]); parameters.addDependency(dependencyModel); idx++; } return new ConstructorModel(realConstructor, parameters); }
@Nullable private static String getNamedAnnotationValue( final Class<?> injectClass, final Class<?> intoClass) { for (final Constructor<?> constructor : intoClass.getConstructors()) { if (!constructor.isAnnotationPresent(Inject.class)) { continue; } final Annotation[][] paramAnnotations = constructor.getParameterAnnotations(); final Class<?>[] paramTypes = constructor.getParameterTypes(); for (int i = 0; i < paramTypes.length; ++i) { if (!injectClass.equals(paramTypes[i])) { continue; } for (int j = 0; j < paramAnnotations[i].length; ++j) { final Annotation paramAnnotation = paramAnnotations[i][j]; if (Named.class.equals(paramAnnotation.annotationType())) { return ((Named) paramAnnotation).value(); } } } } return null; }
// Find matching constructor, if this is an instance method, and populate // constructorDependencies private Optional<MethodHandle> getConstructor( Method method, Map<Set<TypeParameter>, Constructor<?>> constructors) { if (isStatic(method.getModifiers())) { return Optional.empty(); } Constructor<?> constructor = constructors.get(typeParameters); requireNonNull( constructor, format( "%s is an instance method and requires a public constructor to be declared with %s type parameters", method.getName(), typeParameters)); for (int i = 0; i < constructor.getParameterCount(); i++) { Annotation[] annotations = constructor.getParameterAnnotations()[i]; checkArgument( containsMetaParameter(annotations), "Constructors may only have meta parameters"); checkArgument(annotations.length == 1, "Meta parameters may only have a single annotation"); Annotation annotation = annotations[0]; if (annotation instanceof TypeParameter) { checkArgument( typeParameters.contains(annotation), "Injected type parameters must be declared with @TypeParameter annotation on the constructor"); } constructorDependencies.add(parseDependency(annotation)); } try { return Optional.of(lookup().unreflectConstructor(constructor)); } catch (IllegalAccessException e) { throw new PrestoException(FUNCTION_IMPLEMENTATION_ERROR, e); } }
public static Constructor<?> findResourceConstructor(Class<?> resourceClass, boolean perRequest) { List<Constructor<?>> cs = new LinkedList<Constructor<?>>(); for (Constructor<?> c : resourceClass.getConstructors()) { Class<?>[] params = c.getParameterTypes(); Annotation[][] anns = c.getParameterAnnotations(); boolean match = true; for (int i = 0; i < params.length; i++) { if (!perRequest) { if (AnnotationUtils.getAnnotation(anns[i], Context.class) == null) { match = false; break; } } else if (!AnnotationUtils.isValidParamAnnotations(anns[i])) { match = false; break; } } if (match) { cs.add(c); } } Collections.sort( cs, new Comparator<Constructor<?>>() { public int compare(Constructor<?> c1, Constructor<?> c2) { int p1 = c1.getParameterTypes().length; int p2 = c2.getParameterTypes().length; return p1 > p2 ? -1 : p1 < p2 ? 1 : 0; } }); return cs.size() == 0 ? null : cs.get(0); }
InjectionPoint(TypeLiteral<?> declaringType, Constructor<?> constructor) { this.member = constructor; this.declaringType = declaringType; this.optional = false; this.dependencies = forMember(constructor, declaringType, constructor.getParameterAnnotations()); }
public static Object[] createConstructorArguments( Constructor<?> c, Message m, boolean perRequest, Map<Class<?>, Object> contextValues) { Class<?>[] params = c.getParameterTypes(); Annotation[][] anns = c.getParameterAnnotations(); Type[] genericTypes = c.getGenericParameterTypes(); @SuppressWarnings("unchecked") MultivaluedMap<String, String> templateValues = m == null ? null : (MultivaluedMap<String, String>) m.get(URITemplate.TEMPLATE_PARAMETERS); Object[] values = new Object[params.length]; for (int i = 0; i < params.length; i++) { if (AnnotationUtils.getAnnotation(anns[i], Context.class) != null) { Object contextValue = contextValues != null ? contextValues.get(params[i]) : null; if (contextValue == null) { if (perRequest) { values[i] = JAXRSUtils.createContextValue(m, genericTypes[i], params[i]); } else { values[i] = InjectionUtils.createThreadLocalProxy(params[i]); } } else { values[i] = contextValue; } } else { // this branch won't execute for singletons given that the found constructor // is guaranteed to have only Context parameters, if any, for singletons Parameter p = ResourceUtils.getParameter(i, anns[i], params[i]); values[i] = JAXRSUtils.createHttpParameterValue( p, params[i], genericTypes[i], anns[i], m, templateValues, null); } } return values; }
private void bindAutoBindConstructors() { for (Constructor constructor : classpathScanner.getConstructors()) { if (ignoreClasses.contains(constructor.getDeclaringClass())) { continue; } bindParameterAnnotations(constructor.getParameterAnnotations()); } }
public static Object construct( Class<?> klass, Object[] arguments, Map<String, Object> namedArgMap) throws InvocationTargetException, NoSuchMethodException { Objects.requireNonNull(klass, "Class cannot be null"); Objects.requireNonNull(namedArgMap, "Named Argument Map cannot be null"); for (Constructor<?> constructor : klass.getConstructors()) { if (arguments == null) { // null arguments in .newInstance() is allowed if (constructor.getParameterTypes().length != 0) continue; } else if (constructor.getParameterTypes().length != arguments.length) continue; try { Annotation[][] parameterAnnotations = constructor.getParameterAnnotations(); if (arguments == null || arguments.length == 0) { if (LOG.isDebugEnabled()) LOG.debug("Constructor has no arguments"); return constructor.newInstance(arguments); } else if (parameterAnnotations == null || parameterAnnotations.length == 0) { if (LOG.isDebugEnabled()) LOG.debug("Constructor has no parameter annotations"); return constructor.newInstance(arguments); } else { Object[] swizzled = new Object[arguments.length]; int count = 0; for (Annotation[] annotations : parameterAnnotations) { for (Annotation annotation : annotations) { if (annotation instanceof Name) { Name param = (Name) annotation; if (namedArgMap.containsKey(param.value())) { if (LOG.isDebugEnabled()) LOG.debug("placing named {} in position {}", param.value(), count); swizzled[count] = namedArgMap.get(param.value()); } else { if (LOG.isDebugEnabled()) LOG.debug("placing {} in position {}", arguments[count], count); swizzled[count] = arguments[count]; } ++count; } else { if (LOG.isDebugEnabled()) LOG.debug("passing on annotation {}", annotation); } } } return constructor.newInstance(swizzled); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { LOG.ignore(e); } } throw new NoSuchMethodException("<init>"); }
private Annotation[][] getConstrucxtorAnnotations(Class fragmentClass, Constructor constructor) { Annotation[][] parameterAnnotations; if (fragmentClass.getName().endsWith("_Stub")) { try { Class[] constructorParameterTypes = constructor.getParameterTypes(); Class fragmentSuperClass = fragmentClass.getSuperclass(); Constructor realConstructor = fragmentSuperClass.getDeclaredConstructor(constructorParameterTypes); parameterAnnotations = realConstructor.getParameterAnnotations(); } catch (NoSuchMethodException e) { // Shouldn't happen throw new InternalError( "Could not get real constructor of class " + fragmentClass.getName()); } } else { parameterAnnotations = constructor.getParameterAnnotations(); } return parameterAnnotations; }
/** * Return a map with name as the key and index of position as the value for all parameters of the * full constructor in the RMObject * * @param rmClass * @return */ private Map<String, Attribute> attributeMap(Class rmClass) { Map<String, Attribute> map = new HashMap<String, Attribute>(); Constructor constructor = fullConstructor(rmClass); Annotation[][] annotations = constructor.getParameterAnnotations(); for (int i = 0; i < annotations.length; i++) { if (annotations[i].length == 0) { throw new IllegalArgumentException("missing annotation at position " + i); } Attribute attribute = (Attribute) annotations[i][0]; map.put(attribute.name(), attribute); } return map; }
public ResourceConstructor(ResourceClass resourceClass, Constructor constructor) { this.resourceClass = resourceClass; this.constructor = constructor; if (constructor.getParameterTypes() != null) { this.params = new ConstructorParameter[constructor.getParameterTypes().length]; for (int i = 0; i < constructor.getParameterTypes().length; i++) { this.params[i] = new ConstructorParameter( this, constructor.getParameterTypes()[i], constructor.getGenericParameterTypes()[i], constructor.getParameterAnnotations()[i]); } } }
/** @param addParamAnnotations Whether parameter annotations are to be added as well */ protected void _addMixOvers( Constructor<?> mixin, AnnotatedConstructor target, boolean addParamAnnotations) { for (Annotation a : mixin.getDeclaredAnnotations()) { if (_annotationIntrospector.isHandled(a)) { target.addOrOverride(a); } } if (addParamAnnotations) { Annotation[][] pa = mixin.getParameterAnnotations(); for (int i = 0, len = pa.length; i < len; ++i) { for (Annotation a : pa[i]) { target.addOrOverrideParam(i, a); } } } }
void init(Constructor constructor) { for (TypeVariable param : constructor.getTypeParameters()) { typeParameters.add(ElementFactory.getTypeParameterElement(param)); } type = TypeMirrorFactory.get(constructor); enclosingElement = ElementFactory.get(constructor.getDeclaringClass()); returnType = Typ.getNoType(TypeKind.VOID); Type[] genericParameterTypes = constructor.getGenericParameterTypes(); Annotation[][] parameterAnnotations = constructor.getParameterAnnotations(); int index = 0; for (Type param : genericParameterTypes) { parameters.add(ElementFactory.getVariableElement(param, parameterAnnotations[index++])); } varArgs = constructor.isVarArgs(); for (Type type : constructor.getGenericExceptionTypes()) { thrownTypes.add(TypeMirrorFactory.get(type)); } }
public boolean resolve() { Constructor<?>[] constructors = (Constructor<?>[]) type.getConstructors(); Arrays.sort(constructors, CONSTRUCTOR_COMPARATOR); for (Constructor<?> constructor : constructors) { Class<?>[] types = constructor.getParameterTypes(); Annotation[][] annotations = constructor.getParameterAnnotations(); Object[] resolvedArguments = argumentsResolver.resolve(types, annotations); if (resolvedArguments != null) { this.resolvedConstructor = constructor; this.resolvedArguments = resolvedArguments; return true; } } return false; }
private static Collection<? extends MockBinder> createMockBinders(Constructor<?> constructor) { if (constructor.getAnnotation(Inject.class) != null) { HashSet<MockBinder> mockBinders = new HashSet<MockBinder>(); for (int parameterIndex = 0; parameterIndex < constructor.getParameterTypes().length; parameterIndex++) { for (Annotation annotation : constructor.getParameterAnnotations()[parameterIndex]) { if (annotation.annotationType() == Mock.class) { Class<?> mockClass = constructor.getParameterTypes()[parameterIndex]; String mockName = defaultIfEmpty( ((Mock) annotation).value(), uncapitalize(mockClass.getSimpleName())); mockBinders.add(new SimpleMockBinder(mockClass, mockName)); } } } return mockBinders; } else { return Collections.emptyList(); } }
protected boolean matchesConstructor(Type type, java.lang.reflect.Constructor<?> constr) { if (memberName != SpecialName.Constructor) { return false; } if (!matchesEnclosingType(type)) { return false; } Template temp = Utils.getClass(type).getAnnotation(Template.class); Annotation[][] anns = constr.getParameterAnnotations(); Type[] parameterTypes = constr.getGenericParameterTypes(); int overrideOffset = Utils.getEnclosedConstructorParametersOffset(constr); if (!matchesArgs( parameterTypes, anns, overrideOffset + (temp == null ? 0 : temp.value().length))) { return false; } return true; }
/* * Return a map with name as the key and index of position as the value for * required parameters of the full constructor in the RMObject * * @param rmClass @return */ private Map<String, Class> attributeType(Class rmClass) { Map<String, Class> map = new HashMap<String, Class>(); Constructor constructor = fullConstructor(rmClass); if (constructor == null) { throw new IllegalArgumentException("no annotated constructor of " + rmClass + ">"); } Annotation[][] annotations = constructor.getParameterAnnotations(); Class[] types = constructor.getParameterTypes(); if (annotations.length != types.length) { throw new IllegalArgumentException("less annotations"); } for (int i = 0; i < types.length; i++) { if (annotations[i].length == 0) { throw new IllegalArgumentException("missing annotations of attribute " + i); } Attribute attribute = (Attribute) annotations[i][0]; map.put(attribute.name(), types[i]); } return map; }
public void configureClassNode(CompileUnit compileUnit, ClassNode classNode) { try { Class clazz = classNode.getTypeClass(); Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { ClassNode ret = makeClassNode(compileUnit, f.getGenericType(), f.getType()); FieldNode fn = new FieldNode(f.getName(), f.getModifiers(), ret, classNode, null); setAnnotationMetaData(f.getAnnotations(), fn); classNode.addField(fn); } Method[] methods = clazz.getDeclaredMethods(); for (Method m : methods) { ClassNode ret = makeClassNode(compileUnit, m.getGenericReturnType(), m.getReturnType()); Parameter[] params = makeParameters( compileUnit, m.getGenericParameterTypes(), m.getParameterTypes(), m.getParameterAnnotations()); ClassNode[] exceptions = makeClassNodes(compileUnit, m.getGenericExceptionTypes(), m.getExceptionTypes()); MethodNode mn = new MethodNode(m.getName(), m.getModifiers(), ret, params, exceptions, null); mn.setSynthetic(m.isSynthetic()); setMethodDefaultValue(mn, m); setAnnotationMetaData(m.getAnnotations(), mn); mn.setGenericsTypes(configureTypeVariable(m.getTypeParameters())); classNode.addMethod(mn); } Constructor[] constructors = clazz.getDeclaredConstructors(); for (Constructor ctor : constructors) { Parameter[] params = makeParameters( compileUnit, ctor.getGenericParameterTypes(), ctor.getParameterTypes(), ctor.getParameterAnnotations()); ClassNode[] exceptions = makeClassNodes(compileUnit, ctor.getGenericExceptionTypes(), ctor.getExceptionTypes()); classNode.addConstructor(ctor.getModifiers(), params, exceptions, null); } Class sc = clazz.getSuperclass(); if (sc != null) classNode.setUnresolvedSuperClass( makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc)); makeInterfaceTypes(compileUnit, classNode, clazz); setAnnotationMetaData(classNode.getTypeClass().getAnnotations(), classNode); PackageNode packageNode = classNode.getPackage(); if (packageNode != null) { setAnnotationMetaData(classNode.getTypeClass().getPackage().getAnnotations(), packageNode); } } catch (NoClassDefFoundError e) { throw new NoClassDefFoundError( "Unable to load class " + classNode.toString(false) + " due to missing dependency " + e.getMessage()); } catch (MalformedParameterizedTypeException e) { throw new RuntimeException( "Unable to configure class node for class " + classNode.toString(false) + " due to malformed parameterized types", e); } }
/** * Register managed beans as Errai services * * @param event - * @param <T> - */ @SuppressWarnings("UnusedDeclaration") public <T> void observeResources(@Observes final ProcessAnnotatedType<T> event) { final AnnotatedType<T> type = event.getAnnotatedType(); for (final Annotation a : type.getJavaClass().getAnnotations()) { if (a.annotationType().isAnnotationPresent(Qualifier.class)) { beanQualifiers.put(a.annotationType().getName(), a); } } // services if (type.isAnnotationPresent(Service.class)) { log.debug("discovered Errai annotation on type: " + type); boolean isRpc = false; final Class<T> javaClass = type.getJavaClass(); for (final Class<?> intf : javaClass.getInterfaces()) { isRpc = intf.isAnnotationPresent(Remote.class); if (isRpc) { if (!managedTypes.getRemoteInterfaces().contains(intf)) { managedTypes.addRemoteInterface(intf); } } } if (!isRpc) { managedTypes.addServiceEndpoint(type); } } else { for (final AnnotatedMethod method : type.getMethods()) { if (method.isAnnotationPresent(Service.class)) { managedTypes.addServiceMethod(type, method); } } } // veto on client side implementations that contain CDI annotations // (i.e. @Observes) Otherwise Weld might try to invoke on them if (vetoClasses.contains(type.getJavaClass().getName()) || (type.getJavaClass().getPackage().getName().contains("client") && !type.getJavaClass().isInterface())) { event.veto(); } /** We must scan for Event consumer injection points to build the tables */ final Class clazz = type.getJavaClass(); for (final Field f : clazz.getDeclaredFields()) { if (f.isAnnotationPresent(Inject.class) && f.isAnnotationPresent(ObserverModel.class)) { processEventInjector(f.getType(), f.getGenericType(), f.getAnnotations()); } } for (final Method m : clazz.getDeclaredMethods()) { if (m.isAnnotationPresent(Inject.class) && m.isAnnotationPresent(ObserverModel.class)) { final Class<?>[] parameterTypes = m.getParameterTypes(); for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { final Class<?> parmType = parameterTypes[i]; processEventInjector( parmType, m.getGenericParameterTypes()[i], m.getParameterAnnotations()[i]); } } } for (final Constructor c : clazz.getDeclaredConstructors()) { if (c.isAnnotationPresent(Inject.class) && c.isAnnotationPresent(ObserverModel.class)) { final Class<?>[] parameterTypes = c.getParameterTypes(); for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { final Class<?> parmType = parameterTypes[i]; processEventInjector( parmType, c.getGenericParameterTypes()[i], c.getParameterAnnotations()[i]); } } } }
protected AnnotatedConstructor _constructConstructor(Constructor<?> ctor, boolean defaultCtor) { return new AnnotatedConstructor( ctor, _collectRelevantAnnotations(ctor.getDeclaredAnnotations()), defaultCtor ? null : _collectRelevantAnnotations(ctor.getParameterAnnotations())); }
/** * Finds the matching RM class that can be used to create RM object for given value map * * @param valueMap * @return null if no match RM class is found */ public String findMatchingRMClass(Map<String, Object> valueMap) { List simpleTypes = Arrays.asList(SKIPPED_TYPES_IN_MATCHING); for (Class rmClass : typeMap.values()) { log.debug("matching rmClass: " + rmClass.getName()); if (simpleTypes.contains(rmClass.getSimpleName())) { continue; // skip simple value types } // replace underscore separated names with camel case Map<String, Object> filteredMap = new HashMap<String, Object>(); for (String name : valueMap.keySet()) { filteredMap.put(toCamelCase(name), valueMap.get(name)); } Constructor constructor = fullConstructor(rmClass); if (constructor == null) { throw new RuntimeException("annotated constructor missing for " + rmClass); } Annotation[][] annotations = constructor.getParameterAnnotations(); if (annotations == null || annotations.length == 0) { throw new RuntimeException("attribute annotations missing for " + rmClass); } Class[] types = constructor.getParameterTypes(); boolean matched = true; Set<String> attributes = new HashSet<String>(); for (int i = 0; i < types.length; i++) { if (annotations[i].length == 0) { throw new RuntimeException("attribute annotation missing for" + rmClass); } Attribute attribute = (Attribute) annotations[i][0]; attributes.add(attribute.name()); log.debug("checking attribute: " + attribute.name()); String attrName = attribute.name(); Object attrValue = filteredMap.get(attrName); if (attribute.required() && attrValue == null) { log.debug("missing required attribute.."); matched = false; break; } else if (attrValue != null) { if (((attrValue instanceof Boolean) && types[i] != boolean.class) || ((attrValue instanceof Integer) && types[i] != Integer.class) || ((attrValue instanceof Double) && types[i] != double.class)) { log.debug("wrong primitive value type for attribute.."); matched = false; break; } else if (!types[i].isPrimitive() && !types[i].isInstance(attrValue)) { log.debug("wrong value type for attribute.."); matched = false; break; } } } for (String attr : filteredMap.keySet()) { if (!attributes.contains(attr)) { log.debug("unknown attribute: " + attr); matched = false; } } // matching found if (matched) { String className = rmClass.getSimpleName(); log.debug(">>> MATCHING FOUND: " + className); return className; } } return null; }
public static List<ParameterSignature> signatures(Constructor<?> constructor) { return signatures( constructor.getGenericParameterTypes(), constructor.getParameterAnnotations()); }
private static MBeanParameterInfo[] constructorSignature(Constructor cn) { final Class[] classes = cn.getParameterTypes(); final Annotation[][] annots = cn.getParameterAnnotations(); return MBeanOperationInfo.parameters(classes, annots); }