Java Examples for java.lang.reflect.Executable
The following java examples will help you to understand the usage of java.lang.reflect.Executable. These source code samples are taken from different open source projects.
Example 1
| Project: jooby-master File: RequestParamNameProviderImpl.java View source code |
public String name(final Parameter parameter) {
String name = RequestParam.nameFor(parameter);
if (name != null) {
return name;
}
// asm
Executable exec = parameter.getDeclaringExecutable();
Parameter[] params = exec.getParameters();
int idx = IntStream.range(0, params.length).filter( i -> params[i].equals(parameter)).findFirst().getAsInt();
String[] names = nameProvider.names(exec);
return names[idx];
}Example 2
| Project: openjdk-master File: HotSpotResolvedJavaMethodImpl.java View source code |
@Override
public Parameter[] getParameters() {
Executable javaMethod = toJava();
if (javaMethod == null) {
return null;
}
java.lang.reflect.Parameter[] javaParameters = javaMethod.getParameters();
Parameter[] res = new Parameter[javaParameters.length];
for (int i = 0; i < res.length; i++) {
java.lang.reflect.Parameter src = javaParameters[i];
String paramName = src.isNamePresent() ? src.getName() : null;
res[i] = new Parameter(paramName, src.getModifiers(), this, i);
}
return res;
}Example 3
| Project: yangtools-master File: MethodExtensions.java View source code |
public static String toString(Method method) {
StringBuilder sb = new StringBuilder();
sb.append(method.getName());
// copy/paste from java.lang.reflect.Executable.sharedToGenericString(int, boolean)
sb.append('(');
Type[] params = method.getGenericParameterTypes();
// NEW
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.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 4
| Project: hibernate-validator-master File: ValidatorImpl.java View source code |
@Override
public <T> Set<ConstraintViolation<T>> validateParameters(T object, Method method, Object[] parameterValues, Class<?>... groups) {
Contracts.assertNotNull(object, MESSAGES.validatedObjectMustNotBeNull());
Contracts.assertNotNull(method, MESSAGES.validatedMethodMustNotBeNull());
Contracts.assertNotNull(parameterValues, MESSAGES.validatedParameterArrayMustNotBeNull());
return validateParameters(object, (Executable) method, parameterValues, groups);
}Example 5
| Project: cdi-master File: AnnotatedParameter.java View source code |
/**
* Get the underlying {@link Parameter}.
*
* @return the {@link Parameter}
*/
default Parameter getJavaParameter() {
Member member = getDeclaringCallable().getJavaMember();
if (!(member instanceof Executable)) {
throw new IllegalStateException("Parameter does not belong to an executable: " + member);
}
Executable executable = (Executable) member;
return executable.getParameters()[getPosition()];
}Example 6
| Project: AxonFramework-master File: DisruptorCommandBusTest.java View source code |
@Test
public void usesProvidedParameterResolverFactoryToResolveParameters() throws Exception {
testSubject = new DisruptorCommandBus(eventStore);
testSubject.createRepository(new GenericAggregateFactory<>(StubAggregate.class), parameterResolverFactory);
verify(parameterResolverFactory, atLeastOnce()).createInstance(isA(Executable.class), isA(java.lang.reflect.Parameter[].class), anyInt());
verifyNoMoreInteractions(parameterResolverFactory);
}Example 7
| Project: sette-tool-master File: ExecutableComparator.java View source code |
@Override public int compare(Executable o1, Executable o2) { if (o1 == o2) { return 0; } else if (o1 == null) { return -1; } else if (o2 == null) { return 1; } // compare class int cmp = ClassComparator.INSTANCE.compare(o1.getDeclaringClass(), o2.getDeclaringClass()); if (cmp == 0) { // same class, constructors should be before methods cmp = Boolean.compare(o1 instanceof Method, o2 instanceof Method); if (cmp == 0) { // same type, compare name (for constructors it is the same) cmp = o1.getName().compareTo(o2.getName()); if (cmp == 0) { // same name, compare parameter names for (int i = 0; i < Math.min(o1.getParameterCount(), o2.getParameterCount()); i++) { Class<?> p1 = o1.getParameterTypes()[i]; Class<?> p2 = o2.getParameterTypes()[i]; cmp = ClassComparator.INSTANCE.compare(p1, p2); if (cmp != 0) { // different parameter, done return cmp; } } // same beginning of the parameter list, shorter should be before longer return Integer.compare(o1.getParameterCount(), o2.getParameterCount()); } else { return cmp; } } else { return cmp; } } else { return cmp; } }
Example 8
| Project: byte-buddy-master File: AbstractMethodDescriptionTest.java View source code |
@Test
@JavaVersionRule.Enforce(8)
public void testToStringParameter() throws Exception {
Class<?> executable = Class.forName("java.lang.reflect.Executable");
Method method = executable.getDeclaredMethod("getParameters");
assertThat(describe(secondMethod).getParameters().get(0).toString(), is(((Object[]) method.invoke(secondMethod))[0].toString()));
assertThat(describe(secondMethod).getParameters().get(1).toString(), is(((Object[]) method.invoke(secondMethod))[1].toString()));
}Example 9
| Project: core-ng-project-master File: BeanFactory.java View source code |
private Object[] lookupParams(Executable method) {
Type[] paramTypes = method.getGenericParameterTypes();
Annotation[][] paramAnnotations = method.getParameterAnnotations();
Object[] params = new Object[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
Type paramType = stripOutOwnerType(paramTypes[i]);
String name = name(paramAnnotations[i]);
params[i] = bean(paramType, name);
}
return params;
}Example 10
| Project: core-master File: Validator.java View source code |
/**
* Checks for definition errors associated with a given {@link InjectionPoint}
*/
public void validateInjectionPointForDefinitionErrors(InjectionPoint ij, Bean<?> bean, BeanManagerImpl beanManager) {
if (ij.getAnnotated().getAnnotation(New.class) != null && ij.getQualifiers().size() > 1) {
throw ValidatorLogger.LOG.newWithQualifiers(ij, Formats.formatAsStackTraceElement(ij));
}
if (ij.getType() instanceof TypeVariable<?>) {
throw ValidatorLogger.LOG.injectionPointWithTypeVariable(ij, Formats.formatAsStackTraceElement(ij));
}
// WELD-1739
if (ij.getMember() instanceof Executable && ij.getAnnotated().isAnnotationPresent(Named.class) && ij.getAnnotated().getAnnotation(Named.class).value().equals("")) {
Executable executable = (Executable) ij.getMember();
AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();
if (!executable.getParameters()[annotatedParameter.getPosition()].isNamePresent()) {
// No parameters info available
throw ValidatorLogger.LOG.nonFieldInjectionPointCannotUseNamed(ij, Formats.formatAsStackTraceElement(ij));
}
}
if (ij.getAnnotated().isAnnotationPresent(Produces.class)) {
if (bean != null) {
throw BeanLogger.LOG.injectedFieldCannotBeProducer(ij.getAnnotated(), bean);
} else {
throw BeanLogger.LOG.injectedFieldCannotBeProducer(ij.getAnnotated(), Reflections.<AnnotatedField<?>>cast(ij.getAnnotated()).getDeclaringType());
}
}
boolean newBean = (bean instanceof NewBean);
if (!newBean) {
checkScopeAnnotations(ij, beanManager.getServices().get(MetaAnnotationStore.class));
}
checkFacadeInjectionPoint(ij, Instance.class);
checkFacadeInjectionPoint(ij, Event.class);
if (InterceptionFactory.class.equals(Reflections.getRawType(ij.getType())) && !(bean instanceof ProducerMethod<?, ?>)) {
throw ValidatorLogger.LOG.invalidInterceptionFactoryInjectionPoint(ij, Formats.formatAsStackTraceElement(ij));
}
for (PlugableValidator validator : plugableValidators) {
validator.validateInjectionPointForDefinitionErrors(ij, bean, beanManager);
}
}Example 11
| Project: spring-framework-master File: ConstructorResolver.java View source code |
/**
* Create an array of arguments to invoke a constructor or factory method,
* given the resolved constructor argument values.
*/
private ArgumentsHolder createArgumentArray(String beanName, RootBeanDefinition mbd, ConstructorArgumentValues resolvedValues, BeanWrapper bw, Class<?>[] paramTypes, String[] paramNames, Executable executable, boolean autowiring) throws UnsatisfiedDependencyException {
TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
TypeConverter converter = (customConverter != null ? customConverter : bw);
ArgumentsHolder args = new ArgumentsHolder(paramTypes.length);
Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
for (int paramIndex = 0; paramIndex < paramTypes.length; paramIndex++) {
Class<?> paramType = paramTypes[paramIndex];
String paramName = (paramNames != null ? paramNames[paramIndex] : "");
// Try to find matching constructor argument value, either indexed or generic.
ConstructorArgumentValues.ValueHolder valueHolder = resolvedValues.getArgumentValue(paramIndex, paramType, paramName, usedValueHolders);
// it could match after type conversion (for example, String -> int).
if (valueHolder == null && (!autowiring || paramTypes.length == resolvedValues.getArgumentCount())) {
valueHolder = resolvedValues.getGenericArgumentValue(null, null, usedValueHolders);
}
if (valueHolder != null) {
// We found a potential match - let's give it a try.
// Do not consider the same value definition multiple times!
usedValueHolders.add(valueHolder);
Object originalValue = valueHolder.getValue();
Object convertedValue;
if (valueHolder.isConverted()) {
convertedValue = valueHolder.getConvertedValue();
args.preparedArguments[paramIndex] = convertedValue;
} else {
ConstructorArgumentValues.ValueHolder sourceHolder = (ConstructorArgumentValues.ValueHolder) valueHolder.getSource();
Object sourceValue = sourceHolder.getValue();
MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
try {
convertedValue = converter.convertIfNecessary(originalValue, paramType, methodParam);
// TODO re-enable once race condition has been found (SPR-7423)
/*
if (originalValue == sourceValue || sourceValue instanceof TypedStringValue) {
// Either a converted value or still the original one: store converted value.
sourceHolder.setConvertedValue(convertedValue);
args.preparedArguments[paramIndex] = convertedValue;
}
else {
*/
args.resolveNecessary = true;
args.preparedArguments[paramIndex] = sourceValue;
// }
} catch (TypeMismatchException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Could not convert argument value of type [" + ObjectUtils.nullSafeClassName(valueHolder.getValue()) + "] to required type [" + paramType.getName() + "]: " + ex.getMessage());
}
}
args.arguments[paramIndex] = convertedValue;
args.rawArguments[paramIndex] = originalValue;
} else {
MethodParameter methodParam = MethodParameter.forExecutable(executable, paramIndex);
// have to fail creating an argument array for the given constructor.
if (!autowiring) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), "Ambiguous argument values for parameter of type [" + paramType.getName() + "] - did you specify the correct bean references as arguments?");
}
try {
Object autowiredArgument = resolveAutowiredArgument(methodParam, beanName, autowiredBeanNames, converter);
args.rawArguments[paramIndex] = autowiredArgument;
args.arguments[paramIndex] = autowiredArgument;
args.preparedArguments[paramIndex] = new AutowiredArgumentMarker();
args.resolveNecessary = true;
} catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, new InjectionPoint(methodParam), ex);
}
}
}
for (String autowiredBeanName : autowiredBeanNames) {
this.beanFactory.registerDependentBean(autowiredBeanName, beanName);
if (this.beanFactory.logger.isDebugEnabled()) {
this.beanFactory.logger.debug("Autowiring by type from bean name '" + beanName + "' via " + (executable instanceof Constructor ? "constructor" : "factory method") + " to bean named '" + autowiredBeanName + "'");
}
}
return args;
}Example 12
| Project: junit5-master File: ExecutableInvoker.java View source code |
/**
* Resolve the array of parameters for the supplied executable, target, and
* outer instance.
*
* @param executable the executable for which to resolve parameters
* @param target an {@code Optional} containing the target on which the
* executable will be invoked; never {@code null} but should be empty for
* static methods and constructors
* @param outerInstance the outer instance that will be supplied as the
* first argument to a constructor for an inner class; should be {@code null}
* for methods and constructors for top-level or static classes
* @param extensionContext the current {@code ExtensionContext}
* @param extensionRegistry the {@code ExtensionRegistry} to retrieve
* {@code ParameterResolvers} from
* @return the array of Objects to be used as parameters in the executable
* invocation; never {@code null} though potentially empty
*/
private Object[] resolveParameters(Executable executable, Optional<Object> target, Object outerInstance, ExtensionContext extensionContext, ExtensionRegistry extensionRegistry) {
Preconditions.notNull(target, "target must not be null");
Parameter[] parameters = executable.getParameters();
Object[] values = new Object[parameters.length];
int start = 0;
// the executable is a constructor for an inner class.
if (outerInstance != null) {
values[0] = outerInstance;
start = 1;
}
// Resolve remaining parameters dynamically
for (int i = start; i < parameters.length; i++) {
ParameterContext parameterContext = new DefaultParameterContext(parameters[i], i, target);
values[i] = resolveParameter(parameterContext, executable, extensionContext, extensionRegistry);
}
return values;
}Example 13
| Project: Spoon-master File: CtTypeParameterTest.java View source code |
private void checkTypeParamErasureOfExecutable(CtTypeParameter typeParam) throws NoSuchFieldException, SecurityException {
CtExecutable<?> exec = (CtExecutable<?>) typeParam.getParent();
CtParameter<?> param = exec.filterChildren(new NameFilter<>("param" + typeParam.getSimpleName())).first();
assertNotNull("Missing param" + typeParam.getSimpleName() + " in " + exec.getSignature(), param);
int paramIdx = exec.getParameters().indexOf(param);
Class declClass = exec.getParent(CtType.class).getActualClass();
Executable declExec;
if (exec instanceof CtConstructor) {
declExec = declClass.getDeclaredConstructors()[0];
} else {
declExec = getMethodByName(declClass, exec.getSimpleName());
}
Class<?> paramType = declExec.getParameterTypes()[paramIdx];
// contract the type erasure given with Java reflection is the same as the one computed by spoon
assertEquals("TypeErasure of executable param " + getTypeParamIdentification(typeParam), paramType.getName(), typeParam.getTypeErasure().toString());
}Example 14
| Project: Truffle-master File: ClassfileBytecodeProviderTest.java View source code |
private static void checkMethod(ClassfileBytecodeProvider cbp, MetaAccessProvider metaAccess, Executable executable) {
ResolvedJavaMethod method = metaAccess.lookupJavaMethod(executable);
if (method.hasBytecodes()) {
ResolvedJavaMethodBytecode expected = new ResolvedJavaMethodBytecode(method);
Bytecode actual = getBytecode(cbp, method);
new BytecodeComparer(expected, actual).compare();
}
}Example 15
| Project: NOVA-Core-master File: ReflectionUtil.java View source code |
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 16
| Project: eclipselink.runtime-master File: BeanValidationHelper.java View source code |
private boolean detectParameterConstraints(Executable c) {
for (Annotation[] aa : c.getParameterAnnotations()) for (Annotation a : aa) {
final Class<? extends Annotation> annType = a.annotationType();
if (knownConstraints.contains(annType)) {
return true;
}
// detect custom annotations
for (Annotation annOnAnnType : annType.getAnnotations()) {
final Class<? extends Annotation> annTypeOnAnnType = annOnAnnType.annotationType();
if (Constraint.class == annTypeOnAnnType) {
knownConstraints.add(annType);
return true;
}
}
}
return false;
}Example 17
| Project: commons-lang-master File: MemberUtils.java View source code |
/**
* Returns the sum of the object transformation cost for each class in the
* source argument list.
* @param srcArgs The source arguments
* @param executable The executable to calculate transformation costs for
* @return The total transformation cost
*/
private static float getTotalTransformationCost(final Class<?>[] srcArgs, final Executable executable) {
final Class<?>[] destArgs = executable.getParameterTypes();
final boolean isVarArgs = executable.isVarArgs();
// "source" and "destination" are the actual and declared args respectively.
float totalCost = 0.0f;
final long normalArgsLen = isVarArgs ? destArgs.length - 1 : destArgs.length;
if (srcArgs.length < normalArgsLen) {
return Float.MAX_VALUE;
}
for (int i = 0; i < normalArgsLen; i++) {
totalCost += getObjectTransformationCost(srcArgs[i], destArgs[i]);
}
if (isVarArgs) {
// When isVarArgs is true, srcArgs and dstArgs may differ in length.
// There are two special cases to consider:
final boolean noVarArgsPassed = srcArgs.length < destArgs.length;
final boolean explicitArrayForVarags = srcArgs.length == destArgs.length && srcArgs[srcArgs.length - 1].isArray();
final float varArgsCost = 0.001f;
final Class<?> destClass = destArgs[destArgs.length - 1].getComponentType();
if (noVarArgsPassed) {
// When no varargs passed, the best match is the most generic matching type, not the most specific.
totalCost += getObjectTransformationCost(destClass, Object.class) + varArgsCost;
} else if (explicitArrayForVarags) {
final Class<?> sourceClass = srcArgs[srcArgs.length - 1].getComponentType();
totalCost += getObjectTransformationCost(sourceClass, destClass) + varArgsCost;
} else {
// This is typical varargs case.
for (int i = destArgs.length - 1; i < srcArgs.length; i++) {
final Class<?> srcClass = srcArgs[i];
totalCost += getObjectTransformationCost(srcClass, destClass) + varArgsCost;
}
}
}
return totalCost;
}Example 18
| Project: smartass-master File: JavaBridge.java View source code |
static Klass javaClasstoKlass(Class<?> type, ClassValue<Klass> klasses) {
// Java class, not a class generated by the runtime
String klassName = type.getName();
HashMap<String, Function[]> classFunMap = new HashMap<>();
HashMap<String, Function[]> staticFunMap = new HashMap<>();
Klass staticKlass = Klass.create("static-" + klassName, null, Collections.emptyList(), staticFunMap);
staticKlass.registerInitializer( klazz -> {
HashMap<String, ArrayList<Executable>[]> staticMap = new HashMap<>();
gatherMethods(Arrays.<Executable>stream(type.getMethods()).filter(JavaBridge::isStatic), staticMap);
populateKlassWithStaticFields(type, staticFunMap);
populateKlassWithMethods(staticFunMap, staticMap);
Klass klassKlass = klasses.get(Klass.class);
klassKlass.initialize();
staticFunMap.putAll(klassKlass.getMethodMap());
});
Klass klass = Klass.create(klassName, staticKlass, Collections.emptyList(), classFunMap);
klass.registerInitializer( klazz -> {
HashMap<String, ArrayList<Executable>[]> classMap = new HashMap<>();
gatherMethods(Arrays.<Executable>stream(type.getConstructors()), classMap);
gatherMethods(Arrays.<Executable>stream(type.getMethods()).filter(JavaBridge::isNotStatic), classMap);
populateKlassWithMethods(classFunMap, classMap);
});
return klass;
}Example 19
| Project: ProjectAres-master File: Methods.java View source code |
public static void assertPublicThrows(Executable method, Class<?>... exceptions) {
Members.assertPublic(method);
for (Class<?> ex : method.getExceptionTypes()) {
if (!RuntimeException.class.isAssignableFrom(ex)) {
boolean found = false;
for (Class<?> allowed : exceptions) {
if (allowed.isAssignableFrom(ex)) {
found = true;
break;
}
}
if (!found) {
Members.error(method, "throws unhandled exception " + ex.getName());
}
}
}
}Example 20
| Project: bazel-master File: LambdaDesugaring.java View source code |
/**
* Makes {@link #visitEnd} generate a bridge method for the given method handle if the
* referenced method will be invisible to the generated lambda class.
*
* @return struct containing either {@code invokedMethod} or {@code invokedMethod} and a handle
* representing the bridge method that will be generated for {@code invokedMethod}.
*/
private MethodReferenceBridgeInfo queueUpBridgeMethodIfNeeded(Handle invokedMethod) throws ClassNotFoundException {
if (invokedMethod.getName().startsWith("lambda$")) {
// We adjust lambda bodies to be visible
return MethodReferenceBridgeInfo.noBridge(invokedMethod);
}
// invokedMethod is a method reference if we get here
Executable invoked = findTargetMethod(invokedMethod);
if (isVisibleToLambdaClass(invoked, invokedMethod.getOwner())) {
// Referenced method is visible to the generated class, so nothing to do
return MethodReferenceBridgeInfo.noBridge(invokedMethod);
}
// We need a bridge method if we get here
checkState(!isInterface, "%s is an interface and shouldn't need bridge to %s", internalName, invokedMethod);
checkState(!invokedMethod.isInterface(), "%s's lambda classes can't see interface method: %s", internalName, invokedMethod);
MethodReferenceBridgeInfo result = bridgeMethods.get(invokedMethod);
if (result != null) {
// we're already queued up a bridge method for this method reference
return result;
}
String name = uniqueInPackage(internalName, "bridge$lambda$" + bridgeMethods.size());
Handle bridgeMethod;
switch(invokedMethod.getTag()) {
case Opcodes.H_INVOKESTATIC:
bridgeMethod = new Handle(invokedMethod.getTag(), internalName, name, invokedMethod.getDesc(), /*itf*/
false);
break;
case Opcodes.H_INVOKEVIRTUAL:
case // we end up calling these using invokevirtual
Opcodes.H_INVOKESPECIAL:
bridgeMethod = new Handle(Opcodes.H_INVOKEVIRTUAL, internalName, name, invokedMethod.getDesc(), /*itf*/
false);
break;
case Opcodes.H_NEWINVOKESPECIAL:
{
// Call invisible constructor through generated bridge "factory" method, so we need to
// compute the descriptor for the bridge method from the constructor's descriptor
String desc = Type.getMethodDescriptor(Type.getObjectType(invokedMethod.getOwner()), Type.getArgumentTypes(invokedMethod.getDesc()));
bridgeMethod = new Handle(Opcodes.H_INVOKESTATIC, internalName, name, desc, /*itf*/
false);
break;
}
case Opcodes.H_INVOKEINTERFACE:
// Shouldn't get here
default:
throw new UnsupportedOperationException("Cannot bridge " + invokedMethod);
}
result = MethodReferenceBridgeInfo.bridge(invokedMethod, invoked, bridgeMethod);
MethodReferenceBridgeInfo old = bridgeMethods.put(invokedMethod, result);
checkState(old == null, "Already had bridge %s so we don't also want %s", old, result);
return result;
}Example 21
| Project: platypus-master File: Classes2Scripts.java View source code |
private FunctionInfo getFunctionInfo(String defaultName, Executable ae) {
FunctionInfo fi = new FunctionInfo();
ScriptFunction sf = (ScriptFunction) ae.getAnnotation(ScriptFunction.class);
fi.name = sf.name().isEmpty() ? defaultName : sf.name();
fi.apiName = sf.name();
fi.jsDoc = formJsDoc(sf.jsDoc());
fi.params = new String[sf.params().length];
fi.nativeParams = ae.getParameters();
System.arraycopy(sf.params(), 0, fi.params, 0, sf.params().length);
return fi;
}Example 22
| Project: openjdk8-jdk-master File: System.java View source code |
private static void setJavaLangAccess() {
// Allow privileged classes outside of java.lang
sun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess() {
public sun.reflect.ConstantPool getConstantPool(Class<?> klass) {
return klass.getConstantPool();
}
public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {
return klass.casAnnotationType(oldType, newType);
}
public AnnotationType getAnnotationType(Class<?> klass) {
return klass.getAnnotationType();
}
public byte[] getRawClassAnnotations(Class<?> klass) {
return klass.getRawAnnotations();
}
public byte[] getRawClassTypeAnnotations(Class<?> klass) {
return klass.getRawTypeAnnotations();
}
public byte[] getRawExecutableTypeAnnotations(Executable executable) {
return Class.getExecutableTypeAnnotationBytes(executable);
}
public <E extends Enum<E>> E[] getEnumConstantsShared(Class<E> klass) {
return klass.getEnumConstantsShared();
}
public void blockedOn(Thread t, Interruptible b) {
t.blockedOn(b);
}
public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) {
Shutdown.add(slot, registerShutdownInProgress, hook);
}
public int getStackTraceDepth(Throwable t) {
return t.getStackTraceDepth();
}
public StackTraceElement getStackTraceElement(Throwable t, int i) {
return t.getStackTraceElement(i);
}
public String newStringUnsafe(char[] chars) {
return new String(chars, true);
}
});
}Example 23
| Project: quasar-master File: Fiber.java View source code |
@SuppressWarnings("null")
private static boolean checkInstrumentation(ExtendedStackTrace st, boolean fromUncaughtExc) {
if (fromUncaughtExc && st.get().length > 0 && st.get()[0] != null) {
final ExtendedStackTraceElement first = st.get()[0];
if (!first.getDeclaringClass().equals(ClassCastException.class) && !(first.getDeclaringClass().equals(NullPointerException.class) && first.getDeclaringClass().getName().startsWith("co.paralleluniverse.fibers")))
return true;
}
boolean ok = true;
StringBuilder stackTrace = null;
final ExtendedStackTraceElement[] stes = st.get();
for (int i = 0; i < stes.length; i++) {
final ExtendedStackTraceElement ste = stes[i];
if (ste.getClassName().equals(Thread.class.getName()) && ste.getMethodName().equals("getStackTrace"))
continue;
if (ste.getClassName().equals(ExtendedStackTrace.class.getName()))
continue;
if (!ok)
printTraceLine(stackTrace, ste);
if (ste.getClassName().contains("$$Lambda$"))
continue;
if (!ste.getClassName().equals(Fiber.class.getName()) && !ste.getClassName().startsWith(Fiber.class.getName() + '$') && !ste.getClassName().equals(Stack.class.getName()) && !SuspendableHelper.isWaiver(ste.getClassName(), ste.getMethodName())) {
final Class<?> clazz = ste.getDeclaringClass();
final boolean classInstrumented = SuspendableHelper.isInstrumented(clazz);
final /*Executable*/
Member m = SuspendableHelper.lookupMethod(ste);
if (m != null) {
final boolean methodInstrumented = SuspendableHelper.isInstrumented(m);
final Pair<Boolean, Instrumented> callSiteInstrumented = SuspendableHelper.isCallSiteInstrumented(m, ste.getLineNumber(), ste.getBytecodeIndex(), stes, i);
if (!classInstrumented || !methodInstrumented || !callSiteInstrumented.getFirst()) {
if (ok)
stackTrace = initTrace(i, stes);
if (!classInstrumented || !methodInstrumented)
stackTrace.append(" **");
else if (!callSiteInstrumented.getFirst())
stackTrace.append(" !! (instrumented suspendable calls at: ").append(callSitesString(callSiteInstrumented.getSecond())).append(")");
ok = false;
}
} else {
if (ok)
stackTrace = initTrace(i, stes);
// Methods can only be found via source lines in @Instrumented annotations
stackTrace.append(" **");
ok = false;
}
} else if (ste.getClassName().equals(Fiber.class.getName()) && ste.getMethodName().equals("run1")) {
if (!ok) {
final String str = "Uninstrumented whole methods ('**') or single calls ('!!') detected: " + stackTrace;
if (Debug.isUnitTest())
throw new VerifyInstrumentationException(str);
System.err.println("WARNING: " + str);
}
return ok;
}
}
throw new IllegalStateException("Not run through Fiber.exec(). (trace: " + Arrays.toString(stes) + ")");
}Example 24
| Project: eclipse.jdt.core-master File: SerializableLambdaTest.java View source code |
public void testbug479119a() {
this.runConformTest(new String[] { "Testbed.java", "import java.io.ObjectStreamClass;\n" + "import java.io.Serializable;\n" + "import java.lang.invoke.SerializedLambda;\n" + "import java.lang.reflect.Constructor;\n" + "import java.lang.reflect.Executable;\n" + "import java.lang.reflect.Method;\n" + "import java.util.function.IntFunction;\n" + "import java.util.stream.Stream;\n" + "public class Testbed {\n" + " public static void main(String[] args) {\n" + " System.out.println(getMethod(Testbed::foo).equals(getMethod(Testbed::foo)));\n" + " System.out.println(getMethod(new Foo()::method).equals(getMethod(new Bar()::method)));\n" + " System.out.println(getMethod(MethodRefImpl::new).equals(getMethod(MethodRefImpl::new)));\n" + " }\n" + " static class MethodRefImpl implements MethodRef {\n" + " @Override\n" + " public void run() {}\n" + " }\n" + " public static class Base {\n" + " public void method () {}\n" + " }\n" + " public static class Foo extends Base {}\n" + " public static class Bar extends Base {}\n" + " private static void foo() { }\n" + " static interface MethodRef extends Runnable, Serializable { }\n" + " private static Executable getMethod(MethodRef methodRef) {\n" + " try {\n" + " final Method invokeWriteReplaceMethod = ObjectStreamClass.class.getDeclaredMethod(\"invokeWriteReplace\", Object.class);\n" + " invokeWriteReplaceMethod.setAccessible(true);\n" + " final SerializedLambda l = (SerializedLambda)invokeWriteReplaceMethod.invoke(\n" + " ObjectStreamClass.lookupAny(methodRef.getClass()),\n" + " methodRef\n" + " );\n" + " System.out.println(\"Looking for \" + l.getImplClass() + \".\" + l.getImplMethodName());\n" + " boolean isConstructor = l.getImplMethodName().indexOf(\"<init>\") >= 0;\n" + " final Executable[] methods = Stream.of(isConstructor ? Class.forName(l.getImplClass()).getDeclaredConstructors() : Class.forName(l.getImplClass()).getDeclaredMethods()).\n" + " filter(m -> m.getName().equals(isConstructor ? l.getImplClass() : l.getImplMethodName())).\n" + " toArray(isConstructor ? Constructor[]::new : Method[]::new);\n" + " if(methods.length != 1) throw new AssertionError(\"TODO: check signature\");\n" + " return methods[0];\n" + " } catch(Exception e) {\n" + " throw new RuntimeException(e);\n" + " }\n" + " }\n" + "}\n" }, "Looking for Testbed.foo\n" + "Looking for Testbed.foo\n" + "true\n" + "Looking for Testbed$Base.method\n" + "Looking for Testbed$Base.method\n" + "true\n" + "Looking for Testbed$MethodRefImpl.<init>\n" + "Looking for Testbed$MethodRefImpl.<init>\n" + "true", null, true, new String[] { "-Ddummy" });
}Example 25
| Project: mybatis-3-master File: ParamNameUtil.java View source code |
private static List<String> getParameterNames(Executable executable) {
final List<String> names = new ArrayList<String>();
final Parameter[] params = executable.getParameters();
for (Parameter param : params) {
names.add(param.getName());
}
return names;
}Example 26
| Project: vraptor-java8-master File: JavaParameterNameProvider.java View source code |
private java.lang.reflect.Parameter[] getMethodParameters(AccessibleObject executable) {
checkState(executable instanceof Executable, "Only methods or constructors are available");
return ((Executable) executable).getParameters();
}Example 27
| Project: junit-quickcheck-master File: PropertyStatement.java View source code |
private static String declarerName(Parameter p) {
Executable exec = p.getDeclaringExecutable();
return exec.getDeclaringClass().getName() + '.' + exec.getName();
}Example 28
| Project: graal-master File: ReflectionUtils.java View source code |
/**
* Calls {@link AccessibleObject#setAccessible(boolean)} on {@code executable} with the value
* {@code flag}.
*/
public static void setAccessible(Executable executable, boolean flag) {
if (!Java8OrEarlier) {
openForReflectionTo(executable.getDeclaringClass(), ReflectionUtils.class);
}
executable.setAccessible(flag);
}