Search in sources :

Example 46 with Parameter

use of java.lang.reflect.Parameter in project spring-framework by spring-projects.

the class ParameterResolutionTests method resolveDependencyForAnnotatedParametersInTopLevelClassConstructor.

@Test
public void resolveDependencyForAnnotatedParametersInTopLevelClassConstructor() throws Exception {
    Constructor<?> constructor = AutowirableClass.class.getConstructor(String.class, String.class, String.class, String.class);
    AutowireCapableBeanFactory beanFactory = mock(AutowireCapableBeanFactory.class);
    // Configure the mocked BeanFactory to return the DependencyDescriptor for convenience and
    // to avoid using an ArgumentCaptor.
    given(beanFactory.resolveDependency(any(), isNull())).willAnswer(invocation -> invocation.getArgument(0));
    Parameter[] parameters = constructor.getParameters();
    for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) {
        Parameter parameter = parameters[parameterIndex];
        DependencyDescriptor intermediateDependencyDescriptor = (DependencyDescriptor) ParameterResolutionDelegate.resolveDependency(parameter, parameterIndex, AutowirableClass.class, beanFactory);
        assertThat(intermediateDependencyDescriptor.getAnnotatedElement()).isEqualTo(constructor);
        assertThat(intermediateDependencyDescriptor.getMethodParameter().getParameter()).isEqualTo(parameter);
    }
}
Also used : DependencyDescriptor(org.springframework.beans.factory.config.DependencyDescriptor) Parameter(java.lang.reflect.Parameter) AutowireCapableBeanFactory(org.springframework.beans.factory.config.AutowireCapableBeanFactory) Test(org.junit.jupiter.api.Test)

Example 47 with Parameter

use of java.lang.reflect.Parameter in project spring-framework by spring-projects.

the class StandardReflectionParameterNameDiscoverer method getParameterNames.

@Nullable
private String[] getParameterNames(Parameter[] parameters) {
    String[] parameterNames = new String[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
        Parameter param = parameters[i];
        if (!param.isNamePresent()) {
            return null;
        }
        parameterNames[i] = param.getName();
    }
    return parameterNames;
}
Also used : Parameter(java.lang.reflect.Parameter) Nullable(org.springframework.lang.Nullable)

Example 48 with Parameter

use of java.lang.reflect.Parameter in project BuildCraft by BuildCraft.

the class PipeEventBus method getHandlers.

private static List<Handler> getHandlers(Class<?> cls) {
    if (!allHandlers.containsKey(cls)) {
        List<Handler> list = new ArrayList<>();
        Class<?> superCls = cls.getSuperclass();
        if (superCls != null) {
            list.addAll(getHandlers(superCls));
        }
        for (Method m : cls.getDeclaredMethods()) {
            PipeEventHandler annot = m.getAnnotation(PipeEventHandler.class);
            if (annot == null) {
                continue;
            }
            Parameter[] params = m.getParameters();
            if (params.length != 1) {
                throw new IllegalStateException("Cannot annotate " + m + " with @PipeEventHandler as it had an incorrect number of parameters (" + Arrays.toString(params) + ")");
            }
            Parameter p = params[0];
            if (!PipeEvent.class.isAssignableFrom(p.getType())) {
                throw new IllegalStateException("Cannot annotate " + m + " with @PipeEventHandler as it did not take a pipe event! (" + p.getType() + ")");
            }
            MethodHandle mh;
            try {
                mh = MethodHandles.publicLookup().unreflect(m);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException("Cannot annotate " + m + " with @PipeEventHandler as there was a problem with it!", e);
            }
            boolean isStatic = Modifier.isStatic(m.getModifiers());
            String methodName = m.toString();
            list.add(new Handler(annot.priority(), annot.receiveCancelled(), isStatic, methodName, mh, p.getType()));
        }
        allHandlers.put(cls, list);
        return list;
    }
    return allHandlers.get(cls);
}
Also used : ArrayList(java.util.ArrayList) PipeEventHandler(buildcraft.api.transport.pipe.PipeEventHandler) Method(java.lang.reflect.Method) PipeEvent(buildcraft.api.transport.pipe.PipeEvent) PipeEventHandler(buildcraft.api.transport.pipe.PipeEventHandler) Parameter(java.lang.reflect.Parameter) MethodHandle(java.lang.invoke.MethodHandle)

Example 49 with Parameter

use of java.lang.reflect.Parameter in project Network-depr by Mas281.

the class CommandManager method handleMethod.

/**
 * Handles the registering of a command via its method
 *
 * @param object The object containing the method
 * @param method The method to handle
 */
private void handleMethod(Object object, Method method) {
    if (method.isAnnotationPresent(Command.class)) {
        if (method.getParameterCount() < 1) {
            // No parameters, invalid command
            return;
        }
        int paramIndex = -1;
        int minArgs = 0;
        int maxArgs = 0;
        boolean optional = false;
        for (Parameter parameter : method.getParameters()) {
            // There's already been an optional argument
            if (optional) {
                return;
            }
            paramIndex++;
            Class<?> paramClass = parameter.getType();
            if (paramIndex == 0) {
                if (paramClass != User.class) {
                    // First parameter is not a User, invalid command
                    return;
                }
                continue;
            }
            if (!isSupportedParameter(paramClass)) {
                // Parameter with no context found or not String
                return;
            }
            if (parameter.isAnnotationPresent(Optional.class)) {
                optional = true;
            } else {
                minArgs++;
            }
            maxArgs++;
        }
        if (method.getParameterCount() == 1) {
            maxArgs = Integer.MAX_VALUE;
        }
        String[] aliases = method.getDeclaredAnnotation(Command.class).value().split("\\|");
        String usage = getUsage(method);
        Rank requiredRank = getRequiredRank(method);
        Rank[] specificRanks = getSpecificRanks(method);
        CommandData data = new CommandData(object, method, aliases, usage, requiredRank, specificRanks, minArgs, maxArgs);
        commands.add(data);
    }
}
Also used : Parameter(java.lang.reflect.Parameter) RequiredRank(me.itsmas.network.server.command.annotations.RequiredRank) Rank(me.itsmas.network.server.rank.Rank)

Example 50 with Parameter

use of java.lang.reflect.Parameter in project atlasmap by atlasmap.

the class DefaultAtlasFieldActionService method detectFieldActionParameters.

private ActionParameters detectFieldActionParameters(Class<?> actionClazz) throws ClassNotFoundException {
    ActionParameters params = null;
    // Java does not return methods in any consistent order, so sort
    // methods by name to ensure parameter types and values get
    // assigned to the correct method. This means that field actions with
    // multiple parameters must define their setter methods in alphabetical
    // order to be processed correctly. Not an ideal situation, but the only
    // other option would be to force the specification of an order in the
    // AtlasActionProperty annotation via a new parameter, which is also
    // clunky.
    Method[] methods = actionClazz.getMethods();
    Arrays.sort(methods, new Comparator<Method>() {

        @Override
        public int compare(Method method1, Method method2) {
            return method1.getName().compareToIgnoreCase(method2.getName());
        }
    });
    for (Method method : methods) {
        // Find setters to avoid the get / is confusion
        if (method.getParameterCount() == 1 && method.getName().startsWith("set")) {
            // We have a parameter
            if (params == null) {
                params = new ActionParameters();
            }
            ActionParameter actionParam = null;
            for (Parameter methodParam : method.getParameters()) {
                actionParam = new ActionParameter();
                actionParam.setName(camelize(method.getName().substring("set".length())));
                // TODO set displayName/description - https://github.com/atlasmap/atlasmap/issues/96
                actionParam.setFieldType(getConversionService().fieldTypeFromClass(methodParam.getType()));
                // TODO fix this dirty hack for https://github.com/atlasmap/atlasmap/issues/386
                if (methodParam.getType().isEnum()) {
                    actionParam.setFieldType(FieldType.STRING);
                    try {
                        for (Object e : methodParam.getType().getEnumConstants()) {
                            Method m = e.getClass().getDeclaredMethod("value", new Class[0]);
                            actionParam.getValues().add(m.invoke(e, new Object[0]).toString());
                        }
                    } catch (Exception e) {
                        LOG.debug("Failed to populate possible enum parameter values, ignoring...", e);
                    }
                }
                params.getParameter().add(actionParam);
            }
        }
    }
    return params;
}
Also used : ActionParameters(io.atlasmap.v2.ActionParameters) Parameter(java.lang.reflect.Parameter) ActionParameter(io.atlasmap.v2.ActionParameter) Method(java.lang.reflect.Method) ActionParameter(io.atlasmap.v2.ActionParameter) AtlasConversionException(io.atlasmap.api.AtlasConversionException) AtlasException(io.atlasmap.api.AtlasException)

Aggregations

Parameter (java.lang.reflect.Parameter)690 Method (java.lang.reflect.Method)255 ArrayList (java.util.ArrayList)125 Annotation (java.lang.annotation.Annotation)86 List (java.util.List)82 Type (java.lang.reflect.Type)71 HashMap (java.util.HashMap)71 Map (java.util.Map)68 Constructor (java.lang.reflect.Constructor)56 Test (org.junit.jupiter.api.Test)56 Executable (java.lang.reflect.Executable)48 Arrays (java.util.Arrays)47 InvocationTargetException (java.lang.reflect.InvocationTargetException)45 Field (java.lang.reflect.Field)42 ParameterizedType (java.lang.reflect.ParameterizedType)42 Collectors (java.util.stream.Collectors)41 Test (org.junit.Test)41 Optional (java.util.Optional)38 Set (java.util.Set)35 Modifier (java.lang.reflect.Modifier)28