java.lang.reflect.Executable Java Examples

The following examples show how to use java.lang.reflect.Executable. 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: Compiler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #2
Source File: Compiler.java    From jdk8u60 with 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 #3
Source File: RedefineAnnotations.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #4
Source File: CompilerWhiteBoxTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: MultiCommand.java    From openjdk-jdk9 with 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 #6
Source File: DirectiveBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 #7
Source File: IntrinsicBase.java    From openjdk-jdk8u with 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 #8
Source File: InjectorProcessor.java    From panda with 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 #9
Source File: BmiIntrinsicBase.java    From jdk8u60 with 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 #10
Source File: AbstractCommandBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 #11
Source File: DefaultInjectorResources.java    From panda with 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 #12
Source File: MethodParameterFactory.java    From tutorials with 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 #13
Source File: ClassUtils.java    From graphql-spqr with 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 #14
Source File: IntrinsicAvailableTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 #15
Source File: ReflectionPredicates.java    From raistlic-lib-commons-core with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(Executable executable) {

  if (executable == null) {
    return false;
  }
  return Arrays.equals(executable.getParameterTypes(), parameterTypes);
}
 
Example #16
Source File: Compiler.java    From jdk8u60 with 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 #17
Source File: Compiler.java    From TencentKona-8 with 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 #18
Source File: MethodParameterFactory.java    From spring-test-junit5 with 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 #19
Source File: ReflectionPredicates.java    From raistlic-lib-commons-core with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: TypeParser.java    From typescript-generator with 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 #21
Source File: MathIntrinsic.java    From jdk8u60 with 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 #22
Source File: ReflectionUtil.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #23
Source File: SynthesizingMethodParameter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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 #24
Source File: MathIntrinsic.java    From jdk8u60 with 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 #25
Source File: ConstructorResolver.java    From java-technology-stack with 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 #26
Source File: Compiler.java    From hottub with 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 #27
Source File: BmiIntrinsicBase.java    From openjdk-jdk8u with 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 #28
Source File: MathIntrinsic.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
Executable testMethod() throws NoSuchMethodException, ClassNotFoundException {
    return Class.forName("java.lang.Math").getDeclaredMethod("addExact", long.class, long.class);
}
 
Example #29
Source File: WhiteBox.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public        boolean isMethodCompilable(Executable method) {
  return isMethodCompilable(method, -1 /*any*/);
}
 
Example #30
Source File: MathIntrinsic.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
Executable testMethod() throws NoSuchMethodException, ClassNotFoundException {
    return Class.forName("java.lang.Math").getDeclaredMethod("negateExact", int.class);
}