Java Code Examples for java.lang.reflect.Executable

The following examples show how to use java.lang.reflect.Executable. These examples are extracted from open source projects. 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 Project: openjdk-jdk9   Source File: MultiCommand.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a test containing multiple random commands
 *
 * @param validOnly shows that all commands should be valid
 * @return test instance to run
 */
public static AbstractTestBase generateRandomTest(boolean validOnly) {
    CommandGenerator cmdGen = new CommandGenerator();
    List<Command> commands = cmdGen.generateCommands();
    List<CompileCommand> testCases = new ArrayList<>();
    for (Command cmd : commands) {
        if (validOnly && cmd == Command.NONEXISTENT) {
            // replace with a valid command
            cmd = Command.EXCLUDE;
        }
        Executable exec = Utils.getRandomElement(METHODS).first;
        MethodDescriptor md;
        if (validOnly) {
            md = AbstractTestBase.getValidMethodDescriptor(exec);
        } else {
            md = AbstractTestBase.METHOD_GEN.generateRandomDescriptor(exec);
        }
        CompileCommand cc = cmdGen.generateCompileCommand(cmd, md, null);
        testCases.add(cc);
    }
    return new MultiCommand(testCases);
}
 
Example 2
private void verifyMethodTypeAnnotations(Class c)
    throws NoSuchFieldException, NoSuchMethodException {
    Annotation anno;
    Executable typeAnnotatedMethod =
        c.getDeclaredMethod("typeAnnotatedMethod", TypeAnnotatedTestClass.class);

    anno = typeAnnotatedMethod.getAnnotatedReturnType().getAnnotations()[0];
    verifyTestAnn(returnTA, anno, "return");
    returnTA = anno;

    anno = typeAnnotatedMethod.getTypeParameters()[0].getAnnotations()[0];
    verifyTestAnn(methodTypeParameterTA, anno, "methodTypeParameter");
    methodTypeParameterTA = anno;

    anno = typeAnnotatedMethod.getAnnotatedParameterTypes()[0].getAnnotations()[0];
    verifyTestAnn(formalParameterTA, anno, "formalParameter");
    formalParameterTA = anno;

    anno = typeAnnotatedMethod.getAnnotatedExceptionTypes()[0].getAnnotations()[0];
    verifyTestAnn(throwsTA, anno, "throws");
    throwsTA = anno;
}
 
Example 3
private void compileMethod(Executable method, int compLevel) {
    if (WHITE_BOX.isMethodCompilable(method, compLevel)) {
        try {
            WHITE_BOX.enqueueMethodForCompilation(method, compLevel);
            waitCompilation();
            int tmp = WHITE_BOX.getMethodCompilationLevel(method);
            if (tmp != compLevel) {
                logMethod(method, "compilation level = " + tmp
                        + ", but not " + compLevel);
            } else if (Utils.IS_VERBOSE) {
                logMethod(method, "compilation level = " + tmp + ". OK");
            }
        } catch (Throwable t) {
            logMethod(method, "error on compile at " + compLevel
                    + " level");
            t.printStackTrace();
        }
    } else if (Utils.IS_VERBOSE) {
        logMethod(method, "not compilable at " + compLevel);
    }
}
 
Example 4
Source Project: jdk8u60   Source File: Compiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void logMethod(Executable method, String message) {
    StringBuilder builder = new StringBuilder("[");
    builder.append(classId);
    builder.append("]\t");
    builder.append(className);
    builder.append("::");
    builder.append(method.getName());
    builder.append('(');
    Class[] params = method.getParameterTypes();
    for (int i = 0, n = params.length - 1; i < n; ++i) {
        builder.append(params[i].getName());
        builder.append(", ");
    }
    if (params.length != 0) {
        builder.append(params[params.length - 1].getName());
    }
    builder.append(')');
    if (message != null) {
        builder.append('\t');
        builder.append(message);
    }
    System.err.println(builder);
}
 
Example 5
/**
 * Waits for completion of background compilation of the given executable.
 *
 * @param executable Executable
 */
protected static final void waitBackgroundCompilation(Executable executable) {
    if (!BACKGROUND_COMPILATION) {
        return;
    }
    final Object obj = new Object();
    for (int i = 0; i < 100
            && WHITE_BOX.isMethodQueuedForCompilation(executable); ++i) {
        synchronized (obj) {
            try {
                obj.wait(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
 
Example 6
Source Project: openjdk-jdk8u   Source File: IntrinsicBase.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void checkCompilation(Executable executable, int level) {
    if (!WHITE_BOX.isMethodCompiled(executable)) {
        throw new RuntimeException("Test bug, expected compilation (level): " + level + ", but not compiled");
    }
    final int compilationLevel = WHITE_BOX.getMethodCompilationLevel(executable);
    if (compilationLevel != level) {
        if (!(TIERED_COMPILATION && level == COMP_LEVEL_FULL_PROFILE && compilationLevel == COMP_LEVEL_LIMITED_PROFILE)) { //possible case
            throw new RuntimeException("Test bug, expected compilation (level): " + level + ", but level: " + compilationLevel);
        }
    }
}
 
Example 7
public Map<Executable, State> getStates() {
    List<CompileCommand> commandList = new ArrayList<>();
    commandList.addAll(optionCommands);
    commandList.addAll(fileCommands);
    Map<Executable, State> states = new HashMap<>();
    for (Pair<Executable, Callable<?>> pair : METHODS) {
        Executable exec = pair.first;
        State state = getState(commandList, exec);
        states.put(exec, state);
    }
    return states;
}
 
Example 8
Source Project: jdk8u60   Source File: Compiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param classId   id of class
 * @param className name of class
 * @param method    compiled for compilation
 */
public CompileMethodCommand(long classId, String className,
        Executable method) {
    this.classId = classId;
    this.className = className;
    this.method = method;
}
 
Example 9
Source Project: panda   Source File: DefaultInjectorResources.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Annotation[][] fetchAnnotations(Executable executable) {
    Annotation[][] parameterAnnotations = cachedAnnotations.get(executable);

    if (parameterAnnotations == null) {
        parameterAnnotations = executable.getParameterAnnotations();
        cachedAnnotations.put(executable, parameterAnnotations);
    }

    return parameterAnnotations;
}
 
Example 10
Source Project: spring-test-junit5   Source File: MethodParameterFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static int getIndex(Parameter parameter) {
	Assert.notNull(parameter, "Parameter must not be null");
	Executable executable = parameter.getDeclaringExecutable();
	Parameter[] parameters = executable.getParameters();
	for (int i = 0; i < parameters.length; i++) {
		if (parameters[i] == parameter) {
			return i;
		}
	}
	throw new IllegalStateException(String.format("Failed to resolve index of parameter [%s] in executable [%s]",
		parameter, executable.toGenericString()));
}
 
Example 11
static float calculateDistance(Executable exec, Class<?>[] parameterTypes) {
	float cost = 0;

	Class<?>[] execTypes = exec.getParameterTypes();
	for (int i = 0; i < exec.getParameterCount(); i++) {
		if (i >= parameterTypes.length && exec.isVarArgs())
			break;

		Class<?> a = parameterTypes[i];
		Class<?> b = execTypes[i];

		if (i == exec.getParameterCount() - 1 && exec.isVarArgs()) {
			if (isAssignmentCompatible(a, b)) {
				// Passed array for var-args.
				cost += calculateDistance(a, b);
			} else {
				cost += calculateDistance(a, b.getComponentType());
				// Penalty for every parameter that wasn't used.
				cost += (parameterTypes.length - exec.getParameterCount()) * 3F;
				// Death penalty for using var-args.
				cost += 10F;
			}
		} else {
			cost += calculateDistance(a, b);
		}
	}
	return cost;
}
 
Example 12
Source Project: hottub   Source File: Compiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param classId   id of class
 * @param className name of class
 * @param method    compiled for compilation
 */
public CompileMethodCommand(long classId, String className,
        Executable method) {
    this.classId = classId;
    this.className = className;
    this.method = method;
}
 
Example 13
public static Predicate<Executable> executableWithParameterCount(int parametersCount) {

    Precondition.param(parametersCount).greaterThanOrEqualTo(0);

    if (parametersCount == 0) {
      return ExecutableWithParametersCountPredicate.WITH_ZERO;
    }
    if (parametersCount == 1) {
      return ExecutableWithParametersCountPredicate.WITH_ONE;
    }
    return new ExecutableWithParametersCountPredicate(parametersCount);
  }
 
Example 14
@Override
public boolean test(Executable executable) {

  if (executable == null) {
    return false;
  }
  return Arrays.equals(executable.getParameterTypes(), parameterTypes);
}
 
Example 15
protected void checkEmittedCode(Executable executable) {
    final byte[] nativeCode = NMethod.get(executable, false).insts;
    if (!((BmiTestCase) testCase).verifyPositive(nativeCode)) {
        throw new AssertionError(testCase.name() + "CPU instructions expected not found: " + Utils.toHexString(nativeCode));
    } else {
        System.out.println("CPU instructions found, PASSED");
    }
}
 
Example 16
Source Project: graphql-spqr   Source File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the exact annotated parameter types of the executable declared by the given type, with type variables resolved (if possible)
 *
 * @param executable    The executable whose parameter types are to be resolved
 * @param declaringType The declaring annotated type against which to resolve the types of the parameters of the given executable
 * @return The resolved annotated types of the parameters of the given executable
 */
public static AnnotatedType[] getParameterTypes(Executable executable, AnnotatedType declaringType) {
    AnnotatedType exactDeclaringType = GenericTypeReflector.getExactSuperType(capture(declaringType), executable.getDeclaringClass());
    if (isMissingTypeParameters(exactDeclaringType.getType())) {
        return executable.getAnnotatedParameterTypes();
    }
    return GenericTypeReflector.getParameterTypes(executable, declaringType);
}
 
Example 17
Source Project: typescript-generator   Source File: TypeParser.java    License: MIT License 5 votes vote down vote up
private List<Type> getKFunctionParameterTypes(Executable executable, KFunction<?> kFunction) {
    if (kFunction != null) {
        final List<KParameter> kParameters = kFunction.getParameters().stream()
                .filter(kParameter -> kParameter.getKind() == KParameter.Kind.VALUE)
                .collect(Collectors.toList());
        return getTypes(
                kParameters.stream()
                        .map(parameter -> parameter.getType())
                        .collect(Collectors.toList()),
                new LinkedHashMap<>()
        );
    }
    return javaTypeParser.getExecutableParameterTypes(executable);
}
 
Example 18
private State getState(Pair<Executable, Callable<?>> pair) {
    State state = null;
    MethodDescriptor execDesc = MethodGenerator.commandDescriptor(
            pair.first);
    boolean isMatchFound = false;

    if (stateMap.containsKey(pair.first)) {
        state = stateMap.get(pair.first);
    }
    for (MethodDescriptor matchDesc : matchBlocks.keySet()) {
        if (execDesc.getCanonicalString().matches(matchDesc.getRegexp())) {
            /*
             * if executable matches regex
             * then apply commands from this match to the state
             */
            for (CompileCommand cc : matchBlocks.get(matchDesc)) {
                if (state == null) {
                    state = new State();
                }
                if (!isMatchFound) {
                    // this is a first found match, apply all commands
                    state.apply(cc);
                } else {
                    // apply only inline directives
                    switch (cc.command) {
                        case INLINE:
                        case DONTINLINE:
                            state.apply(cc);
                            break;
                    }
                }
            }
            isMatchFound = true;
        }
    }
    return state;
}
 
Example 19
Source Project: java-technology-stack   Source File: ConstructorResolver.java    License: MIT License 5 votes vote down vote up
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(String beanName, RootBeanDefinition mbd, BeanWrapper bw,
		Executable executable, Object[] argsToResolve, boolean fallback) {

	TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
	TypeConverter converter = (customConverter != null ? customConverter : bw);
	BeanDefinitionValueResolver valueResolver =
			new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
	Class<?>[] paramTypes = executable.getParameterTypes();

	Object[] resolvedArgs = new Object[argsToResolve.length];
	for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
		Object argValue = argsToResolve[argIndex];
		MethodParameter methodParam = MethodParameter.forExecutable(executable, argIndex);
		GenericTypeResolver.resolveParameterType(methodParam, executable.getDeclaringClass());
		if (argValue instanceof AutowiredArgumentMarker) {
			argValue = resolveAutowiredArgument(methodParam, beanName, null, converter, fallback);
		}
		else if (argValue instanceof BeanMetadataElement) {
			argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
		}
		else if (argValue instanceof String) {
			argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
		}
		Class<?> paramType = paramTypes[argIndex];
		try {
			resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
		}
		catch (TypeMismatchException ex) {
			throw new UnsatisfiedDependencyException(
					mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam),
					"Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(argValue) +
					"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
		}
	}
	return resolvedArgs;
}
 
Example 20
Source Project: jdk8u60   Source File: MathIntrinsic.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Executable getExecutable() {
    try {
        return getClass().getDeclaredMethod("execMathMethod");
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Test bug, no such method: " + e);
    }
}
 
Example 21
/**
 * Create a new SynthesizingMethodParameter for the given method or constructor.
 * <p>This is a convenience factory method for scenarios where a
 * Method or Constructor reference is treated in a generic fashion.
 * @param executable the Method or Constructor to specify a parameter for
 * @param parameterIndex the index of the parameter
 * @return the corresponding SynthesizingMethodParameter instance
 * @since 5.0
 */
public static SynthesizingMethodParameter forExecutable(Executable executable, int parameterIndex) {
	if (executable instanceof Method) {
		return new SynthesizingMethodParameter((Method) executable, parameterIndex);
	}
	else if (executable instanceof Constructor) {
		return new SynthesizingMethodParameter((Constructor<?>) executable, parameterIndex);
	}
	else {
		throw new IllegalArgumentException("Not a Method/Constructor: " + executable);
	}
}
 
Example 22
Source Project: jdk8u60   Source File: MathIntrinsic.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Executable getExecutable() {
    try {
        return getClass().getDeclaredMethod("execMathMethod");
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Test bug, no such method: " + e);
    }
}
 
Example 23
Source Project: TencentKona-8   Source File: Compiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param classId   id of class
 * @param className name of class
 * @param method    compiled for compilation
 */
public CompileMethodCommand(long classId, String className,
        Executable method) {
    this.classId = classId;
    this.className = className;
    this.method = method;
}
 
Example 24
public void test() throws Exception {
    Executable intrinsicMethod = testCase.getExecutable();
    if (Platform.isServer() && !Platform.isEmulatedClient() && (TIERED_STOP_AT_LEVEL == COMP_LEVEL_FULL_OPTIMIZATION)) {
        if (TIERED_COMPILATION) {
            checkIntrinsicForCompilationLevel(intrinsicMethod, COMP_LEVEL_SIMPLE);
        }
        // Dont bother check JVMCI compiler - returns false on all intrinsics.
        if (!Boolean.valueOf(getVMOption("UseJVMCICompiler"))) {
            checkIntrinsicForCompilationLevel(intrinsicMethod, COMP_LEVEL_FULL_OPTIMIZATION);
        }
    } else {
        checkIntrinsicForCompilationLevel(intrinsicMethod, COMP_LEVEL_SIMPLE);
    }
}
 
Example 25
Source Project: tutorials   Source File: MethodParameterFactory.java    License: MIT License 5 votes vote down vote up
private static int getIndex(Parameter parameter) {
    Assert.notNull(parameter, "Parameter must not be null");
    Executable executable = parameter.getDeclaringExecutable();
    Parameter[] parameters = executable.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        if (parameters[i] == parameter) {
            return i;
        }
    }
    throw new IllegalStateException(String.format("Failed to resolve index of parameter [%s] in executable [%s]", parameter, executable.toGenericString()));
}
 
Example 26
Source Project: jdk8u60   Source File: BmiIntrinsicBase.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void checkEmittedCode(Executable executable) {
    final byte[] nativeCode = NMethod.get(executable, false).insts;
    if (!((BmiTestCase) testCase).verifyPositive(nativeCode)) {
        throw new AssertionError(testCase.name() + "CPU instructions expected not found: " + Utils.toHexString(nativeCode));
    } else {
        System.out.println("CPU instructions found, PASSED");
    }
}
 
Example 27
Source Project: panda   Source File: InjectorProcessor.java    License: Apache License 2.0 5 votes vote down vote up
protected Collection<InjectorResourceHandler<Annotation, Object, ?>>[] fetchHandlers(Executable executable) {
    Collection<InjectorResourceHandler<Annotation, Object, ?>>[] handlers = ObjectUtils.cast(new Collection[executable.getParameterCount()]);
    Parameter[] parameters = executable.getParameters();

    for (int index = 0; index < parameters.length; index++) {
        handlers[index] = injector.getResources().getHandler(parameters[index]);
    }

    return handlers;
}
 
Example 28
private TestCase(Executable executable, Callable<Integer> callable,
        boolean isOsr) {
    this.executable = executable;
    this.callable = callable;
    this.isOsr = isOsr;
}
 
Example 29
Source Project: byte-buddy   Source File: OriginExecutableWithCache.java    License: Apache License 2.0 4 votes vote down vote up
public Executable intercept(@Origin(cache = true) Executable executable) {
    this.executable = executable;
    return executable;
}
 
Example 30
Source Project: jdk8u_jdk   Source File: Class.java    License: GNU General Public License v2.0 4 votes vote down vote up
static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
    return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
}