Search in sources :

Example 51 with Parameter

use of java.lang.reflect.Parameter in project Summer by yale8848.

the class MethodsProcessor method get.

public static ClassInfo get(List<ClassInfo> classInfos, Class clazz) {
    Path path = (Path) clazz.getAnnotation(Path.class);
    if (path == null || path.value() == null) {
        return null;
    }
    ClassInfo classInfo = new ClassInfo();
    classInfo.setClassPath(path.value());
    classInfo.setClazzObj(newClass(clazz));
    classInfo.setClazz(clazz);
    Interceptor[] interceptorsClazz = getBefores((Before) clazz.getAnnotation(Before.class));
    if (interceptorsClazz != null) {
        classInfo.setBefores(interceptorsClazz);
    }
    interceptorsClazz = getAfters((After) clazz.getAnnotation(After.class));
    if (interceptorsClazz != null) {
        classInfo.setAfters(interceptorsClazz);
    }
    for (Method method : clazz.getMethods()) {
        Class mt = method.getDeclaringClass();
        if (mt == Object.class) {
            continue;
        }
        MethodInfo methodInfo = new MethodInfo();
        Interceptor[] interceptorsMethod = getBefores((Before) method.getAnnotation(Before.class));
        if (interceptorsMethod != null) {
            methodInfo.setBefores(interceptorsMethod);
        }
        interceptorsMethod = getAfters((After) method.getAnnotation(After.class));
        if (interceptorsMethod != null) {
            methodInfo.setAfters(interceptorsMethod);
        }
        Blocking blocking = method.getAnnotation(Blocking.class);
        if (blocking != null) {
            methodInfo.setBlocking(true);
        }
        Path pathMthod = (Path) method.getAnnotation(Path.class);
        Produces produces = (Produces) method.getAnnotation(Produces.class);
        methodInfo.setMethodPath(getPathValue(pathMthod));
        methodInfo.setProducesType(getProducesValue(produces));
        methodInfo.setHttpMethod(getHttpMethod(method));
        methodInfo.setMethod(method);
        Parameter[] parameters = method.getParameters();
        Class<?>[] parameterTypes = method.getParameterTypes();
        Annotation[][] annotations = method.getParameterAnnotations();
        int i = 0;
        for (Annotation[] an : annotations) {
            ArgInfo argInfo = new ArgInfo();
            argInfo.setAnnotation(an);
            argInfo.setClazz(parameterTypes[i]);
            argInfo.setParameter(parameters[i]);
            for (Annotation ant : an) {
                if (ant instanceof Context) {
                    argInfo.setContext(true);
                } else if (ant instanceof DefaultValue) {
                    argInfo.setDefaultValue(((DefaultValue) ant).value());
                } else if (ant instanceof PathParam) {
                    argInfo.setPathParam(true);
                    argInfo.setPathParam(((PathParam) ant).value());
                } else if (ant instanceof QueryParam) {
                    argInfo.setQueryParam(true);
                    argInfo.setQueryParam(((QueryParam) ant).value());
                } else if (ant instanceof FormParam) {
                    argInfo.setFormParam(true);
                    argInfo.setFormParam(((FormParam) ant).value());
                }
            }
            i++;
            methodInfo.addArgInfo(argInfo);
        }
        classInfo.addMethodInfo(methodInfo);
    }
    classInfos.add(classInfo);
    return classInfo;
}
Also used : Context(javax.ws.rs.core.Context) Blocking(ren.yale.java.annotation.Blocking) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) ArgInfo(ren.yale.java.method.ArgInfo) After(ren.yale.java.aop.After) Parameter(java.lang.reflect.Parameter) MethodInfo(ren.yale.java.method.MethodInfo) Interceptor(ren.yale.java.interceptor.Interceptor) ClassInfo(ren.yale.java.method.ClassInfo)

Example 52 with Parameter

use of java.lang.reflect.Parameter in project ZenScript by CraftTweaker.

the class JavaMethod method getOptionalValue.

/**
 * Creates the value for the optional Expression
 *
 * @param position    position
 * @param javaMethod  Method to calculate for
 * @param parameterNr which parameter
 * @param environment ZS environment (used for ZS types and Expression creation)
 *
 * @return default optional (0, false, null) or default value according to the @Optional annotation
 */
private static Expression getOptionalValue(ZenPosition position, JavaMethod javaMethod, int parameterNr, IEnvironmentGlobal environment) {
    Parameter parameter = javaMethod.getMethod().getParameters()[parameterNr];
    Optional optional = parameter.getAnnotation(Optional.class);
    // No annotation (not sure how but lets be sure) -> Default value
    if (optional == null)
        return javaMethod.getParameterTypes()[parameterNr].defaultValue(position);
    Class<?> parameterType = parameter.getType();
    // Primitives
    if (parameterType.isPrimitive()) {
        Class<?> clazz = parameter.getType();
        if (clazz == int.class || clazz == short.class || clazz == long.class || clazz == byte.class)
            return new ExpressionInt(position, optional.valueLong(), environment.getType(clazz));
        else if (clazz == boolean.class)
            return new ExpressionBool(position, optional.valueBoolean());
        else if (clazz == float.class || clazz == double.class)
            return new ExpressionFloat(position, optional.valueDouble(), environment.getType(clazz));
        else {
            // Should never happen
            environment.error(position, "Optional Annotation Error, not a known primitive: " + clazz);
            return new ExpressionInvalid(position);
        }
    }
    Class<?> methodClass = optional.methodClass();
    if (methodClass == Optional.class) {
        // Backwards compat!
        return (parameterType == String.class && !optional.value().isEmpty()) ? new ExpressionString(position, optional.value()) : javaMethod.getParameterTypes()[parameterNr].defaultValue(position);
    }
    try {
        Method method = methodClass.getMethod(optional.methodName(), String.class);
        if (!parameterType.isAssignableFrom(method.getReturnType())) {
            environment.error(position, "Optional Annotation Error, cannot assign " + parameterType + " from " + method);
            return new ExpressionInvalid(position);
        }
        return new ExpressionCallStatic(position, environment, new JavaMethod(method, environment.getEnvironment().getTypeRegistry()), new ExpressionString(position, optional.value()));
    } catch (NoSuchMethodException ignored) {
        // Method not found --> Null
        environment.error(position, "Optional Annotation Error, cannot find method " + optional.methodName());
        return new ExpressionInvalid(position);
    }
}
Also used : Optional(stanhebben.zenscript.annotations.Optional) ParsedZenClassMethod(stanhebben.zenscript.definitions.zenclasses.ParsedZenClassMethod) Method(java.lang.reflect.Method) Parameter(java.lang.reflect.Parameter)

Example 53 with Parameter

use of java.lang.reflect.Parameter in project flow by vaadin.

the class PolymerServerEventHandlers method getParameters.

private String[] getParameters(Method method) {
    List<String> result = new ArrayList<>();
    for (Parameter parameter : method.getParameters()) {
        EventData eventData = parameter.getAnnotation(EventData.class);
        if (eventData != null) {
            result.add(eventData.value());
        }
        if (ReflectTools.hasAnnotation(parameter, REPEAT_INDEX_FQN)) {
            result.add(REPEAT_INDEX_VALUE);
        }
        Optional<Annotation> annotation = ReflectTools.getAnnotation(parameter, MODEL_ITEM_FQN);
        if (annotation.isPresent()) {
            result.add(ReflectTools.getAnnotationMethodValue(annotation.get(), VALUE).toString());
        }
    }
    return result.toArray(new String[result.size()]);
}
Also used : ArrayList(java.util.ArrayList) Parameter(java.lang.reflect.Parameter) EventData(com.vaadin.flow.component.EventData) Annotation(java.lang.annotation.Annotation)

Example 54 with Parameter

use of java.lang.reflect.Parameter in project flow by vaadin.

the class ComponentEventBusUtil method findEventDataExpressions.

/**
 * Scans the event type and forms a map of event data expression (for
 * {@link com.vaadin.flow.dom.DomListenerRegistration#addEventData(String)}
 * ) to Java type, with the same order as the parameters for the event
 * constructor (as returned by {@link #getEventConstructor(Class)}).
 *
 * @return a map of event data expressions, in the order defined by the
 *         component event constructor parameters
 */
private static LinkedHashMap<String, Class<?>> findEventDataExpressions(Constructor<? extends ComponentEvent<?>> eventConstructor) {
    LinkedHashMap<String, Class<?>> eventDataExpressions = new LinkedHashMap<>();
    // Parameter 1 is always "boolean fromClient"
    for (int i = 2; i < eventConstructor.getParameterCount(); i++) {
        Parameter p = eventConstructor.getParameters()[i];
        EventData eventData = p.getAnnotation(EventData.class);
        if (eventData == null || eventData.value().isEmpty()) {
            // @DomEvent, or its value is empty."
            throw new IllegalArgumentException(String.format("The parameter %s of the constructor %s has no @%s, or the annotation value is empty", p.getName(), eventConstructor.toString(), EventData.class.getSimpleName()));
        }
        eventDataExpressions.put(eventData.value(), p.getType());
    }
    return eventDataExpressions;
}
Also used : Parameter(java.lang.reflect.Parameter) LinkedHashMap(java.util.LinkedHashMap)

Example 55 with Parameter

use of java.lang.reflect.Parameter in project Terasology by MovingBlocks.

the class ObjectLayoutBuilder method populateConstructorParameters.

private void populateConstructorParameters(Binding<T> binding, ColumnLayout parameterLayout, UIButton createInstanceButton, Binding<Constructor<T>> selectedConstructor) {
    parameterLayout.removeAllWidgets();
    Parameter[] parameters = selectedConstructor.get().getParameters();
    List<TypeInfo<?>> parameterTypes = Arrays.stream(parameters).map(Parameter::getParameterizedType).map(parameterType -> ReflectionUtil.resolveType(type.getType(), parameterType)).map(TypeInfo::of).collect(Collectors.toList());
    List<Binding<?>> argumentBindings = parameterTypes.stream().map(parameterType -> new DefaultBinding<>(Defaults.defaultValue(parameterType.getRawType()))).collect(Collectors.toList());
    createInstanceButton.subscribe(widget -> {
        Object[] arguments = argumentBindings.stream().map(Binding::get).toArray();
        try {
            binding.set(selectedConstructor.get().newInstance(arguments));
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    });
    if (argumentBindings.isEmpty()) {
        // TODO: Translate
        parameterLayout.addWidget(new UILabel("Constructor has no parameters"));
        return;
    }
    ColumnLayout parametersExpandableLayout = WidgetUtil.createExpandableLayout(// TODO: Translate
    "Constructor Parameters", this::createDefaultLayout, layout -> {
        for (int i = 0; i < parameterTypes.size(); i++) {
            TypeInfo<?> parameterType = parameterTypes.get(i);
            Binding<?> argumentBinding = argumentBindings.get(i);
            Parameter parameter = parameters[i];
            Optional<UIWidget> optionalWidget = library.getBaseTypeWidget((Binding) argumentBinding, parameterType);
            if (!optionalWidget.isPresent()) {
                LOGGER.warn("Could not create widget for parameter of type {} of constructor {}", parameter, selectedConstructor.get());
                continue;
            }
            UIWidget widget = optionalWidget.get();
            String parameterLabelText = ReflectionUtil.typeToString(parameterType.getType(), true);
            layout.addWidget(WidgetUtil.labelize(widget, parameterLabelText, LABEL_WIDGET_ID));
        }
    }, this::createDefaultLayout);
    parameterLayout.addWidget(parametersExpandableLayout);
}
Also used : NotifyingBinding(org.terasology.nui.databinding.NotifyingBinding) DefaultBinding(org.terasology.nui.databinding.DefaultBinding) Binding(org.terasology.nui.databinding.Binding) Arrays(java.util.Arrays) Defaults(com.google.common.base.Defaults) LoggerFactory(org.slf4j.LoggerFactory) TypeWidgetLibrary(org.terasology.nui.widgets.types.TypeWidgetLibrary) TypeInfo(org.terasology.reflection.TypeInfo) ExpandableLayoutBuilder(org.terasology.nui.widgets.types.builtin.util.ExpandableLayoutBuilder) FieldsWidgetBuilder(org.terasology.nui.widgets.types.builtin.util.FieldsWidgetBuilder) WidgetUtil(org.terasology.nui.WidgetUtil) Constructor(java.lang.reflect.Constructor) UIBox(org.terasology.nui.widgets.UIBox) NotifyingBinding(org.terasology.nui.databinding.NotifyingBinding) DefaultBinding(org.terasology.nui.databinding.DefaultBinding) ColumnLayout(org.terasology.nui.layouts.ColumnLayout) Parameter(java.lang.reflect.Parameter) StringTextRenderer(org.terasology.nui.itemRendering.StringTextRenderer) Binding(org.terasology.nui.databinding.Binding) UIDropdownScrollable(org.terasology.nui.widgets.UIDropdownScrollable) Logger(org.slf4j.Logger) UILabel(org.terasology.nui.widgets.UILabel) ReflectionUtil(org.terasology.engine.utilities.ReflectionUtil) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) UIWidget(org.terasology.nui.UIWidget) List(java.util.List) UIButton(org.terasology.nui.widgets.UIButton) LABEL_WIDGET_ID(org.terasology.nui.widgets.types.TypeWidgetFactory.LABEL_WIDGET_ID) Optional(java.util.Optional) UILabel(org.terasology.nui.widgets.UILabel) DefaultBinding(org.terasology.nui.databinding.DefaultBinding) TypeInfo(org.terasology.reflection.TypeInfo) InvocationTargetException(java.lang.reflect.InvocationTargetException) UIWidget(org.terasology.nui.UIWidget) ColumnLayout(org.terasology.nui.layouts.ColumnLayout) Parameter(java.lang.reflect.Parameter)

Aggregations

Parameter (java.lang.reflect.Parameter)701 Method (java.lang.reflect.Method)258 ArrayList (java.util.ArrayList)129 Annotation (java.lang.annotation.Annotation)89 List (java.util.List)85 Type (java.lang.reflect.Type)73 HashMap (java.util.HashMap)73 Map (java.util.Map)70 Constructor (java.lang.reflect.Constructor)58 Test (org.junit.jupiter.api.Test)56 InvocationTargetException (java.lang.reflect.InvocationTargetException)50 Executable (java.lang.reflect.Executable)48 Arrays (java.util.Arrays)47 Field (java.lang.reflect.Field)44 ParameterizedType (java.lang.reflect.ParameterizedType)44 Collectors (java.util.stream.Collectors)41 Test (org.junit.Test)41 Optional (java.util.Optional)40 Set (java.util.Set)37 Modifier (java.lang.reflect.Modifier)30