Java Code Examples for java.lang.reflect.Method#isVarArgs()

The following examples show how to use java.lang.reflect.Method#isVarArgs() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MethodElementHandler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the result of method execution.
 *
 * @param type  the base class
 * @param args  the array of arguments
 * @return the value of this element
 * @throws Exception if calculation is failed
 */
@Override
protected ValueObject getValueObject(Class<?> type, Object[] args) throws Exception {
    Object bean = getContextBean();
    Class<?>[] types = getArgumentTypes(args);
    Method method = (type != null)
            ? MethodFinder.findStaticMethod(type, this.name, types)
            : MethodFinder.findMethod(bean.getClass(), this.name, types);

    if (method.isVarArgs()) {
        args = getArguments(args, method.getParameterTypes());
    }
    Object value = MethodUtil.invoke(method, bean, args);
    return method.getReturnType().equals(void.class)
            ? ValueObjectImpl.VOID
            : ValueObjectImpl.create(value);
}
 
Example 2
Source File: MethodElementHandler.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the result of method execution.
 *
 * @param type  the base class
 * @param args  the array of arguments
 * @return the value of this element
 * @throws Exception if calculation is failed
 */
@Override
protected ValueObject getValueObject(Class<?> type, Object[] args) throws Exception {
    Object bean = getContextBean();
    Class<?>[] types = getArgumentTypes(args);
    Method method = (type != null)
            ? MethodFinder.findStaticMethod(type, this.name, types)
            : MethodFinder.findMethod(bean.getClass(), this.name, types);

    if (method.isVarArgs()) {
        args = getArguments(args, method.getParameterTypes());
    }
    Object value = MethodUtil.invoke(method, bean, args);
    return method.getReturnType().equals(void.class)
            ? ValueObjectImpl.VOID
            : ValueObjectImpl.create(value);
}
 
Example 3
Source File: JavaClass.java    From Digital with GNU General Public License v3.0 6 votes vote down vote up
private MyMethod(Method method) {
    this.method = method;
    this.isStatic = Modifier.isStatic(method.getModifiers());

    Class<?>[] argTypes = method.getParameterTypes();
    javaArgCount = argTypes.length;
    addContext = (argTypes.length > 0 && argTypes[0].isAssignableFrom(Context.class));

    isVarArgs = method.isVarArgs();
    if (isVarArgs) {
        argCount = -1;
        compType = argTypes[argTypes.length - 1].getComponentType();
    } else {
        if (addContext)
            argCount = argTypes.length - 1;
        else
            argCount = argTypes.length;
        compType = null;
    }
}
 
Example 4
Source File: MethodElementHandler.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the result of method execution.
 *
 * @param type  the base class
 * @param args  the array of arguments
 * @return the value of this element
 * @throws Exception if calculation is failed
 */
@Override
protected ValueObject getValueObject(Class<?> type, Object[] args) throws Exception {
    Object bean = getContextBean();
    Class<?>[] types = getArgumentTypes(args);
    Method method = (type != null)
            ? MethodFinder.findStaticMethod(type, this.name, types)
            : MethodFinder.findMethod(bean.getClass(), this.name, types);

    if (method.isVarArgs()) {
        args = getArguments(args, method.getParameterTypes());
    }
    Object value = MethodUtil.invoke(method, bean, args);
    return method.getReturnType().equals(void.class)
            ? ValueObjectImpl.VOID
            : ValueObjectImpl.create(value);
}
 
Example 5
Source File: FunctionReference.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute a function represented as a java.lang.reflect.Method.
 * @param state the expression evaluation state
 * @param method the method to invoke
 * @return the return value of the invoked Java method
 * @throws EvaluationException if there is any problem invoking the method
 */
private TypedValue executeFunctionJLRMethod(ExpressionState state, Method method) throws EvaluationException {
	this.method = null;
	Object[] functionArgs = getArguments(state);

	if (!method.isVarArgs() && method.getParameterTypes().length != functionArgs.length) {
		throw new SpelEvaluationException(SpelMessage.INCORRECT_NUMBER_OF_ARGUMENTS_TO_FUNCTION,
				functionArgs.length, method.getParameterTypes().length);
	}
	// Only static methods can be called in this way
	if (!Modifier.isStatic(method.getModifiers())) {
		throw new SpelEvaluationException(getStartPosition(),
				SpelMessage.FUNCTION_MUST_BE_STATIC, ClassUtils.getQualifiedMethodName(method), this.name);
	}

	this.argumentConversionOccurred = false;
	// Convert arguments if necessary and remap them for varargs if required
	if (functionArgs != null) {
		TypeConverter converter = state.getEvaluationContext().getTypeConverter();
		this.argumentConversionOccurred = ReflectionHelper.convertAllArguments(converter, functionArgs, method);
	}
	if (method.isVarArgs()) {
		functionArgs = ReflectionHelper.setupArgumentsForVarargsInvocation(
				method.getParameterTypes(), functionArgs);
	}

	try {
		ReflectionUtils.makeAccessible(method);
		Object result = method.invoke(method.getClass(), functionArgs);
		if (!argumentConversionOccurred) {
			this.method = method;
			this.exitTypeDescriptor = CodeFlow.toDescriptor(method.getReturnType());
		}
		return new TypedValue(result, new TypeDescriptor(new MethodParameter(method, -1)).narrow(result));
	}
	catch (Exception ex) {
		throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_FUNCTION_CALL,
				this.name, ex.getMessage());
	}
}
 
Example 6
Source File: JwtValidationGenerator.java    From tomee with Apache License 2.0 5 votes vote down vote up
protected void generateMethods(final ClassWriter cw) {
    for (final MethodConstraints methodConstraints : constraints) {
        final Method method = methodConstraints.getMethod();
        final String name = method.getName();

        // Declare a method of return type JsonWebToken for use with
        // a call to BeanValidation's ExecutableValidator.validateReturnValue
        final Type returnType = Type.getType(JsonWebToken.class);
        final Type[] parameterTypes = Type.getArgumentTypes(method);
        final String descriptor = Type.getMethodDescriptor(returnType, parameterTypes);

        final int access = method.isVarArgs() ? ACC_PUBLIC + ACC_VARARGS : ACC_PUBLIC;

        final MethodVisitor mv = cw.visitMethod(access, name, descriptor, null, null);

        // Put the method name on the
        final AnnotationVisitor av = mv.visitAnnotation(Type.getDescriptor(Generated.class), true);
        av.visit("value", this.getClass().getName());
        av.visitEnd();

        // track the MethodVisitor
        // We will later copy over the annotations
        generatedMethods.put(method.getName() + Type.getMethodDescriptor(method), new ConstrainedMethodVisitor(mv, methodConstraints));

        // The method will simply return null
        mv.visitCode();
        mv.visitInsn(ACONST_NULL);
        mv.visitInsn(ARETURN);
        mv.visitMaxs(1, 1);
    }
}
 
Example 7
Source File: LimiterExecutionContext.java    From Limiter with Apache License 2.0 5 votes vote down vote up
private Object[] extractArgs(Method method, Object[] args) {
    if (!method.isVarArgs()) {
        return args;
    } else {
        Object[] varArgs = ObjectUtils.toObjectArray(args[args.length - 1]);
        Object[] combinedArgs = new Object[args.length - 1 + varArgs.length];
        System.arraycopy(args, 0, combinedArgs, 0, args.length - 1);
        System.arraycopy(varArgs, 0, combinedArgs, args.length - 1, varArgs.length);
        return combinedArgs;
    }
}
 
Example 8
Source File: MethodExtensions.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
public static String toString(final Method method) {
    final StringBuilder sb = new StringBuilder();
    sb.append(method.getName());

    // copy/paste from java.lang.reflect.Executable.sharedToGenericString(int, boolean)
    sb.append('(');
    final Type[] params = method.getGenericParameterTypes();
    // NEW
    final Parameter[] parameters = method.getParameters();
    for (int j = 0; j < params.length; j++) {
        String param = params[j].getTypeName();
        if (method.isVarArgs() && j == params.length - 1) {
            // replace T[] with T...
            param = PARAM_PATTERN.matcher(param).replaceFirst("...");
        }
        sb.append(param);
        // NEW
        if (parameters[j].isNamePresent()) {
            sb.append(' ');
            sb.append(parameters[j].getName());
        }
        // NEW END
        if (j < params.length - 1) {
            // NEW ", " instead of ','
            sb.append(", ");
        }
    }
    sb.append(')');

    return sb.toString();
}
 
Example 9
Source File: MethodKey.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether a method accepts a variable number of arguments.
 * <p>May be due to a subtle bug in some JVMs, if a varargs method is an override, depending on (may be) the
 * class introspection order, the isVarargs flag on the method itself will be false.
 * To circumvent the potential problem, fetch the method with the same signature from the super-classes,
 * - which will be different if override  -and get the varargs flag from it.
 * @param method the method to check for varargs
 * @return true if declared varargs, false otherwise
 */
public static boolean isVarArgs(final Method method) {
    if (method == null) {
        return false;
    }
    if (method.isVarArgs()) {
        return true;
    }
    // before climbing up the hierarchy, verify that the last parameter is an array
    final Class<?>[] ptypes = method.getParameterTypes();
    if (ptypes.length == 0 || ptypes[ptypes.length - 1].getComponentType() == null) {
        return false;
    }
    final String mname = method.getName();
    // if this is an override, was it actually declared as varargs?
    Class<?> clazz = method.getDeclaringClass();
    do {
        try {
            Method m = clazz.getMethod(mname, ptypes);
            if (m.isVarArgs()) {
                return true;
            }
        } catch (NoSuchMethodException xignore) {
            // this should not happen...
        }
        clazz = clazz.getSuperclass();
    } while(clazz != null);
    return false;
}
 
Example 10
Source File: ClassReader.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static long getMemberFlag(Method member){
    int flag=member.getModifiers();
    if(member.isSynthetic()) flag|=SYNTHETIC;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N&&member.isDefault()) {
        flag|=DEFAULT;
    }
    if(member.isBridge()) flag|=BRIDGE;
    if(member.isVarArgs()) flag|=VARARGS;
    return flag;
}
 
Example 11
Source File: DynMethods.java    From kite with Apache License 2.0 4 votes vote down vote up
UnboundMethod(Method method, String name) {
  this.method = method;
  this.name = name;
  this.argLength = (method == null || method.isVarArgs()) ? -1 :
      method.getParameterTypes().length;
}
 
Example 12
Source File: DynMethods.java    From iceberg with Apache License 2.0 4 votes vote down vote up
UnboundMethod(Method method, String name) {
  this.method = method;
  this.name = name;
  this.argLength = (method == null || method.isVarArgs()) ? -1 :
      method.getParameterTypes().length;
}
 
Example 13
Source File: JavaAdapterBytecodeGenerator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static int getAccessModifiers(final Method method) {
    return ACC_PUBLIC | (method.isVarArgs() ? ACC_VARARGS : 0);
}
 
Example 14
Source File: JavaAdapterBytecodeGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static int getAccessModifiers(final Method method) {
    return ACC_PUBLIC | (method.isVarArgs() ? ACC_VARARGS : 0);
}
 
Example 15
Source File: JavaAdapterBytecodeGenerator.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private static int getAccessModifiers(final Method method) {
    return ACC_PUBLIC | (method.isVarArgs() ? ACC_VARARGS : 0);
}
 
Example 16
Source File: FunctionReference.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Execute a function represented as a {@code java.lang.reflect.Method}.
 * @param state the expression evaluation state
 * @param method the method to invoke
 * @return the return value of the invoked Java method
 * @throws EvaluationException if there is any problem invoking the method
 */
private TypedValue executeFunctionJLRMethod(ExpressionState state, Method method) throws EvaluationException {
	Object[] functionArgs = getArguments(state);

	if (!method.isVarArgs()) {
		int declaredParamCount = method.getParameterCount();
		if (declaredParamCount != functionArgs.length) {
			throw new SpelEvaluationException(SpelMessage.INCORRECT_NUMBER_OF_ARGUMENTS_TO_FUNCTION,
					functionArgs.length, declaredParamCount);
		}
	}
	if (!Modifier.isStatic(method.getModifiers())) {
		throw new SpelEvaluationException(getStartPosition(),
				SpelMessage.FUNCTION_MUST_BE_STATIC, ClassUtils.getQualifiedMethodName(method), this.name);
	}

	// Convert arguments if necessary and remap them for varargs if required
	TypeConverter converter = state.getEvaluationContext().getTypeConverter();
	boolean argumentConversionOccurred = ReflectionHelper.convertAllArguments(converter, functionArgs, method);
	if (method.isVarArgs()) {
		functionArgs = ReflectionHelper.setupArgumentsForVarargsInvocation(
				method.getParameterTypes(), functionArgs);
	}
	boolean compilable = false;

	try {
		ReflectionUtils.makeAccessible(method);
		Object result = method.invoke(method.getClass(), functionArgs);
		compilable = !argumentConversionOccurred;
		return new TypedValue(result, new TypeDescriptor(new MethodParameter(method, -1)).narrow(result));
	}
	catch (Exception ex) {
		throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_FUNCTION_CALL,
				this.name, ex.getMessage());
	}
	finally {
		if (compilable) {
			this.exitTypeDescriptor = CodeFlow.toDescriptor(method.getReturnType());
			this.method = method;
		}
		else {
			this.exitTypeDescriptor = null;
			this.method = null;
		}
	}
}
 
Example 17
Source File: JavaAdapterBytecodeGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static int getAccessModifiers(final Method method) {
    return ACC_PUBLIC | (method.isVarArgs() ? ACC_VARARGS : 0);
}
 
Example 18
Source File: UtilityManagerUtils.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public static Object[] getReflectionArgs(Method method, Object... args) {
    if(args == null) {
        return NULL_ARGUMENT_ARRAY;
    }

    if(!method.isVarArgs()) {
        return args;
    }

    Class<?>[] signatureClasses = method.getParameterTypes();
    int signatureLength = signatureClasses.length;

    if(signatureLength == 0) {
        return ArrayUtils.EMPTY_OBJECT_ARRAY;
    }

    int lastIndex = signatureLength - 1;
    Class<?> varArgsClass = signatureClasses[lastIndex].getComponentType();
    Object varArgsArray = getVarArgsArray(args, lastIndex, ClassUtils.primitiveToWrapper(varArgsClass));
    Object[] newArgs = new Object[signatureLength];

    System.arraycopy(args, 0, newArgs, 0, signatureLength - 1);

    if(varArgsClass.isPrimitive()) {
        if(varArgsClass.equals(boolean.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Boolean[])varArgsArray);
        } else if(varArgsClass.equals(byte.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Byte[])varArgsArray);
        } else if(varArgsClass.equals(short.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Short[])varArgsArray);
        } else if(varArgsClass.equals(char.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Character[])varArgsArray);
        } else if(varArgsClass.equals(int.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Integer[])varArgsArray);
        } else if(varArgsClass.equals(float.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Float[])varArgsArray);
        } else if(varArgsClass.equals(long.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Long[])varArgsArray);
        } else if(varArgsClass.equals(double.class)) {
            varArgsArray = ArrayUtils.toPrimitive((Double[])varArgsArray);
        }
    }

    newArgs[lastIndex] = varArgsArray;

    return newArgs;
}
 
Example 19
Source File: SpelNodeImpl.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generate code that handles building the argument values for the specified method. This method will take account
 * of whether the invoked method is a varargs method and if it is then the argument values will be appropriately
 * packaged into an array.
 * @param mv the method visitor where code should be generated
 * @param cf the current codeflow
 * @param member the method or constructor for which arguments are being setup
 * @param arguments the expression nodes for the expression supplied argument values
 */
protected static void generateCodeForArguments(MethodVisitor mv, CodeFlow cf, Member member, SpelNodeImpl[] arguments) {
	String[] paramDescriptors = null;
	boolean isVarargs = false;
	if (member instanceof Constructor) {
		Constructor<?> ctor = (Constructor<?>)member;
		paramDescriptors = CodeFlow.toDescriptors(ctor.getParameterTypes());
		isVarargs = ctor.isVarArgs();
	}
	else { // Method
		Method method = (Method)member;
		paramDescriptors = CodeFlow.toDescriptors(method.getParameterTypes());
		isVarargs = method.isVarArgs();
	}
	if (isVarargs) {
		// The final parameter may or may not need packaging into an array, or nothing may
		// have been passed to satisfy the varargs and so something needs to be built.
		int p = 0; // Current supplied argument being processed
		int childCount = arguments.length;
					
		// Fulfill all the parameter requirements except the last one
		for (p = 0; p < paramDescriptors.length - 1; p++) {
			generateCodeForArgument(mv, cf, arguments[p], paramDescriptors[p]);
		}
		
		SpelNodeImpl lastchild = (childCount == 0 ? null : arguments[childCount - 1]);
		String arraytype = paramDescriptors[paramDescriptors.length - 1];
		// Determine if the final passed argument is already suitably packaged in array
		// form to be passed to the method
		if (lastchild != null && lastchild.getExitDescriptor().equals(arraytype)) {
			generateCodeForArgument(mv, cf, lastchild, paramDescriptors[p]);
		}
		else {
			arraytype = arraytype.substring(1); // trim the leading '[', may leave other '['		
			// build array big enough to hold remaining arguments
			CodeFlow.insertNewArrayCode(mv, childCount - p, arraytype);
			// Package up the remaining arguments into the array
			int arrayindex = 0;
			while (p < childCount) {
				SpelNodeImpl child = arguments[p];
				mv.visitInsn(DUP);
				CodeFlow.insertOptimalLoad(mv, arrayindex++);
				generateCodeForArgument(mv, cf, child, arraytype);
				CodeFlow.insertArrayStore(mv, arraytype);
				p++;
			}
		}
	}
	else {
		for (int i = 0; i < paramDescriptors.length;i++) {
			generateCodeForArgument(mv, cf, arguments[i], paramDescriptors[i]);
		}
	}
}
 
Example 20
Source File: ReflectionHelper.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Convert a supplied set of arguments into the requested types. If the parameterTypes are related to
 * a varargs method then the final entry in the parameterTypes array is going to be an array itself whose
 * component type should be used as the conversion target for extraneous arguments. (For example, if the
 * parameterTypes are {Integer, String[]} and the input arguments are {Integer, boolean, float} then both
 * the boolean and float must be converted to strings). This method does *not* repackage the arguments
 * into a form suitable for the varargs invocation - a subsequent call to setupArgumentsForVarargsInvocation handles that.
 * @param converter the converter to use for type conversions
 * @param arguments the arguments to convert to the requested parameter types
 * @param method the target Method
 * @return true if some kind of conversion occurred on the argument
 * @throws SpelEvaluationException if there is a problem with conversion
 */
public static boolean convertAllArguments(TypeConverter converter, Object[] arguments, Method method)
		throws SpelEvaluationException {

	Integer varargsPosition = (method.isVarArgs() ? method.getParameterCount() - 1 : null);
	return convertArguments(converter, arguments, method, varargsPosition);
}