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

The following examples show how to use java.lang.reflect.Method#isDefault() . 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
/**
 * Test if this method should be skipped in our check for proper forwarding, e.g. because it is just a bridge.
 */
private static boolean checkSkipMethodForwardCheck(Method delegateMethod, Set<Method> skipMethods) {

	if (delegateMethod.isBridge()
		|| delegateMethod.isDefault()
		|| skipMethods.contains(delegateMethod)) {
		return true;
	}

	// skip methods declared in Object (Mockito doesn't like them)
	try {
		Object.class.getMethod(delegateMethod.getName(), delegateMethod.getParameterTypes());
		return true;
	} catch (Exception ignore) {
	}
	return false;
}
 
Example 2
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    // Give our delegate a chance to intercept, and cache the decision
    if(delegatedMethods.get(method, () -> method.getDeclaringClass() != Object.class &&
                                          Methods.hasOverrideIn(Delegate.class, method))) {
        return method.invoke(delegate, args);
    }

    // If we have a value for the property, return that
    final Object value = values.get(method);
    if(value != null) return value;

    // If there's no value, then the method MUST be callable (or the code is broken).
    // This can only fail for an abstract non-property method (which we should probably be checking for).
    if(method.isDefault()) {
        // invokeSuper doesn't understand default methods
        return defaultMethodHandles.get(method)
                                   .bindTo(obj)
                                   .invokeWithArguments(args);
    } else {
        return proxy.invokeSuper(obj, args);
    }
}
 
Example 3
Source Project: flink   File: MethodForwardingTestUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test if this method should be skipped in our check for proper forwarding, e.g. because it is just a bridge.
 */
private static boolean checkSkipMethodForwardCheck(Method delegateMethod, Set<Method> skipMethods) {

	if (delegateMethod.isBridge()
		|| delegateMethod.isDefault()
		|| skipMethods.contains(delegateMethod)) {
		return true;
	}

	// skip methods declared in Object (Mockito doesn't like them)
	try {
		Object.class.getMethod(delegateMethod.getName(), delegateMethod.getParameterTypes());
		return true;
	} catch (Exception ignore) {
	}
	return false;
}
 
Example 4
Source Project: jdk8u_jdk   File: Class.java    License: GNU General Public License v2.0 6 votes vote down vote up
void removeLessSpecifics() {
    if (!hasDefaults())
        return;

    for (int i = 0; i < length; i++) {
        Method m = get(i);
        if  (m == null || !m.isDefault())
            continue;

        for (int j  = 0; j < length; j++) {
            if (i == j)
                continue;

            Method candidate = get(j);
            if (candidate == null)
                continue;

            if (!matchesNameAndDescriptor(m, candidate))
                continue;

            if (hasMoreSpecificClass(m, candidate))
                remove(j);
        }
    }
}
 
Example 5
Source Project: hottub   File: Class.java    License: GNU General Public License v2.0 6 votes vote down vote up
void removeLessSpecifics() {
    if (!hasDefaults())
        return;

    for (int i = 0; i < length; i++) {
        Method m = get(i);
        if  (m == null || !m.isDefault())
            continue;

        for (int j  = 0; j < length; j++) {
            if (i == j)
                continue;

            Method candidate = get(j);
            if (candidate == null)
                continue;

            if (!matchesNameAndDescriptor(m, candidate))
                continue;

            if (hasMoreSpecificClass(m, candidate))
                remove(j);
        }
    }
}
 
Example 6
void removeLessSpecifics() {
    if (!hasDefaults())
        return;

    for (int i = 0; i < length; i++) {
        Method m = get(i);
        if  (m == null || !m.isDefault())
            continue;

        for (int j  = 0; j < length; j++) {
            if (i == j)
                continue;

            Method candidate = get(j);
            if (candidate == null)
                continue;

            if (!matchesNameAndDescriptor(m, candidate))
                continue;

            if (hasMoreSpecificClass(m, candidate))
                remove(j);
        }
    }
}
 
Example 7
void add(Method m) {
    if (length == methods.length) {
        methods = Arrays.copyOf(methods, 2 * methods.length);
    }
    methods[length++] = m;

    if (m != null && m.isDefault())
        defaults++;
}
 
Example 8
public ReactiveServiceInterface createReactiveServiceInterface(String group, String version,
                                                               String serviceFullName, Class<?> javaInterface) {
    ReactiveServiceInterface serviceInterface = new ReactiveServiceInterface();
    serviceInterface.setGroup(group);
    serviceInterface.setVersion(version);
    serviceInterface.setNamespace(javaInterface.getPackage().getName());
    serviceInterface.setName(javaInterface.getSimpleName());
    Deprecated interfaceDeprecated = javaInterface.getAnnotation(Deprecated.class);
    if (interfaceDeprecated != null) {
        serviceInterface.setDeprecated(true);
    }
    for (Method method : javaInterface.getMethods()) {
        if (!method.isDefault()) {
            String handlerName = method.getName();
            ReactiveOperation operation = new ReactiveOperation();
            Deprecated methodDeprecated = method.getAnnotation(Deprecated.class);
            if (methodDeprecated != null) {
                operation.setDeprecated(true);
            }
            serviceInterface.addOperation(operation);
            operation.setName(handlerName);
            operation.setReturnType(method.getReturnType().getCanonicalName());
            operation.setReturnInferredType(ReactiveMethodSupport.parseInferredClass(method.getGenericReturnType()).getCanonicalName());
            for (Parameter parameter : method.getParameters()) {
                OperationParameter param = new OperationParameter();
                operation.addParameter(param);
                param.setName(parameter.getName());
                param.setType(parameter.getType().getCanonicalName());
                String inferredType = ReactiveMethodSupport.parseInferredClass(parameter.getParameterizedType()).getCanonicalName();
                if (!param.getType().equals(inferredType)) {
                    param.setInferredType(inferredType);
                }
            }
        }
    }
    return serviceInterface;
}
 
Example 9
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.isDefault()) {
        return ReflectionExt.invokeDefault(proxy, apiInterface, method, args);
    }

    MethodHandler wrapper = methodWrappers.get(method);
    if (wrapper != null) {
        return wrapper.get();
    }
    // Must be one of the Object methods.
    return method.invoke(this);
}
 
Example 10
@Override
public DataProvideDefinition getProvider(MultipleArgumentsFunction<?> multipleArgumentsFunction) throws IllegalAccessException {
    DataProvideDefinition provider = repository.get(multipleArgumentsFunction.getClass().getName());
    if(provider != null) {
        return provider;
    }
    Method[] methods = multipleArgumentsFunction.getClass().getMethods();
    Method applyMethod = null;


    for (Method method : methods) {
        if(! Modifier.isStatic(method.getModifiers()) && ! method.isDefault()) {
            applyMethod = method;
            break;
        }
    }

    if(applyMethod == null) {
        throw new IllegalAccessException(multipleArgumentsFunction.getClass().getName());
    }

    provider = DefinitionUtils.getProvideDefinition(applyMethod);
    provider.setTarget(multipleArgumentsFunction);
    provider.setId(multipleArgumentsFunction.getClass().getName());
    repository.put(provider);
    return provider;
}
 
Example 11
@Override
public Object invoke( Object proxy, Method method, Object[] args )
    throws Throwable
{
    if( method.isDefault() )
    {
        // Call the interface's default method
        MethodCallHandler callHandler = forMethod( method );
        return callHandler.invoke( proxy, args );
    }
    // call the composite's method instead.
    return method.invoke( me, args );
}
 
Example 12
@Override
public ResultHolder handle(T target, Object proxy, Method method, Object[] args) throws Throwable {
	if(method.isDefault()) {
	Class<?> declaringClass = method.getDeclaringClass();
	MethodHandles.Lookup lookup = Reflect.onClass(MethodHandles.Lookup.class)
			.create(declaringClass, MethodHandles.Lookup.PRIVATE).get();
	return new ResultHolder(lookup.unreflectSpecial(method, declaringClass)
				  .bindTo(proxy)
				  .invokeWithArguments(args));
	} else return null;
}
 
Example 13
Source Project: jdk8u60   File: Class.java    License: GNU General Public License v2.0 5 votes vote down vote up
void add(Method m) {
    if (length == methods.length) {
        methods = Arrays.copyOf(methods, 2 * methods.length);
    }
    methods[length++] = m;

    if (m != null && m.isDefault())
        defaults++;
}
 
Example 14
private static boolean isAnyGetter(Method method) {
    return method.getParameterCount() == 0 && !method.isDefault() && !method.isSynthetic()
            && (method.getModifiers() & Modifier.STATIC) == 0
            && method.getReturnType() != Void.TYPE;
}
 
Example 15
Source Project: bazel   File: DefaultMethodClassFixer.java    License: Apache License 2.0 4 votes vote down vote up
private void recordInheritedMethods() {
  InstanceMethodRecorder recorder =
      new InstanceMethodRecorder(mayNeedInterfaceStubsForEmulatedSuperclass());
  if (newSuperName != null) {
    checkState(useGeneratedBaseClasses);
    // If we're using a generated base class, walk the implemented interfaces and record default
    // methods we won't need to stub.  That reflects the methods that will be in the generated
    // base class (and its superclasses, if applicable), without looking at the generated class.
    // We go through sub-interfaces before their super-interfaces (same order as when we stub)
    // to encounter overriding before overridden default methods.  We don't record methods from
    // interfaces the chosen base class doesn't implement, even if those methods also appear in
    // interfaces we would normally record later.  That ensures we generate a stub when a default
    // method is available in the base class but needs to be overridden due to an overriding
    // default method in a sub-interface not implemented by the base class.
    LinkedHashSet<String> allSeen = new LinkedHashSet<>();
    for (Class<?> itf : interfacesToStub) {
      boolean willBeInBaseClass = itf.isAssignableFrom(newSuperName);
      for (Method m : itf.getDeclaredMethods()) {
        if (!m.isDefault()) {
          continue;
        }
        String desc = Type.getMethodDescriptor(m);
        if (coreLibrarySupport != null) {
          // Foreshadow any type renaming to avoid issues with double-desugaring (b/111447199)
          desc = coreLibrarySupport.getRemapper().mapMethodDesc(desc);
        }
        String methodKey = m.getName() + ":" + desc;
        if (allSeen.add(methodKey) && willBeInBaseClass) {
          // Only record never-seen methods, and only for super-types of newSuperName (see longer
          // explanation above)
          instanceMethods.add(methodKey);
        }
      }
    }

    // Fall through to the logic below to record j.l.Object's methods.
    checkState(superName.equals("java/lang/Object"));
  }

  // Walk superclasses
  String internalName = superName;
  while (internalName != null) {
    ClassReader bytecode = bootclasspath.readIfKnown(internalName);
    if (bytecode == null) {
      bytecode =
          checkNotNull(
              classpath.readIfKnown(internalName), "Superclass not found: %s", internalName);
    }
    bytecode.accept(recorder, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
    internalName = bytecode.getSuperName();
  }
}
 
Example 16
Source Project: cxf   File: CDIInterceptorWrapperImpl.java    License: Apache License 2.0 4 votes vote down vote up
private static Map<Method, List<InterceptorInvoker>> initInterceptorInvokers(BeanManager beanManager,
                                                                             CreationalContext<?> creationalContext,
                                                                             Class<?> restClient) {
    Map<Method, List<InterceptorInvoker>> invokers = new HashMap<>();
    // Interceptor as a key in a map is not entirely correct (custom interceptors) but should work in most cases
    Map<Interceptor<?>, Object> interceptorInstances = new HashMap<>();
    
    AnnotatedType<?> restClientType = beanManager.createAnnotatedType(restClient);

    List<Annotation> classBindings = getBindings(restClientType.getAnnotations(), beanManager);

    for (AnnotatedMethod<?> method : restClientType.getMethods()) {
        Method javaMethod = method.getJavaMember();
        if (javaMethod.isDefault() || method.isStatic()) {
            continue;
        }
        List<Annotation> methodBindings = getBindings(method.getAnnotations(), beanManager);

        if (!classBindings.isEmpty() || !methodBindings.isEmpty()) {
            Annotation[] interceptorBindings = merge(methodBindings, classBindings);

            List<Interceptor<?>> interceptors =
                new ArrayList<>(beanManager.resolveInterceptors(InterceptionType.AROUND_INVOKE, 
                                                                interceptorBindings));
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.finest("Resolved interceptors from beanManager, " + beanManager + ":" + interceptors);
            }

            if (!interceptors.isEmpty()) {
                List<InterceptorInvoker> chain = new ArrayList<>();
                for (Interceptor<?> interceptor : interceptors) {
                    chain.add(
                        new InterceptorInvoker(interceptor, 
                                               interceptorInstances.computeIfAbsent(interceptor, 
                                                   i -> beanManager.getReference(i, 
                                                                                 i.getBeanClass(), 
                                                                                 creationalContext))));
                }
                invokers.put(javaMethod, chain);
            }
        }
    }
    return invokers.isEmpty() ? Collections.emptyMap() : invokers;
}
 
Example 17
Source Project: spring-fabric-gateway   File: TypeResolver.java    License: MIT License 4 votes vote down vote up
private static boolean isDefaultMethod(Method m) {
	return JAVA_VERSION >= 1.8 && m.isDefault();
}
 
Example 18
Source Project: gadtry   File: MethodInfo.java    License: Apache License 2.0 4 votes vote down vote up
public static MethodInfo of(Method method)
{
    return new MethodInfo()
    {
        @Override
        public String getName()
        {
            return method.getName();
        }

        @Override
        public Class<?> getReturnType()
        {
            return method.getReturnType();
        }

        @Override
        public int getModifiers()
        {
            return method.getModifiers();
        }

        @Override
        public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
        {
            return method.getAnnotation(annotationClass);
        }

        @Override
        public Annotation[] getAnnotations()
        {
            return method.getAnnotations();
        }

        @Override
        public Class<?>[] getParameterTypes()
        {
            return method.getParameterTypes();
        }

        @Override
        public int getParameterCount()
        {
            return method.getParameterCount();
        }

        @Override
        public Class<?>[] getExceptionTypes()
        {
            return method.getExceptionTypes();
        }

        @Override
        public boolean isDefault()
        {
            return method.isDefault();
        }

        @Override
        public Annotation[][] getParameterAnnotations()
        {
            return method.getParameterAnnotations();
        }

        @Override
        public boolean isVarArgs()
        {
            return method.isVarArgs();
        }

        @Override
        public String toString()
        {
            Map<String, Object> helper = new HashMap<>();
            helper.put("name", getName());
            helper.put("returnType", getReturnType());
            helper.put("modifiers", getModifiers());
            helper.put("Annotations", MutableList.<Annotation>of(method.getAnnotations()));
            helper.put("method", method);
            return super.toString() + helper.toString();
        }
    };
}
 
Example 19
Source Project: component-runtime   File: Defaults.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isDefaultAndShouldHandle(final Method method) {
    return method.isDefault();
}
 
Example 20
Source Project: JALSE   File: Functions.java    License: Apache License 2.0 2 votes vote down vote up
/**
    * Checks whether the method is not default.
    *
    * @param m
    *            Method to check.
    * @throws IllegalArgumentException
    *             If method is default.
    */
   public static void checkNotDefault(final Method m) throws IllegalArgumentException {
if (m.isDefault()) {
    throw new IllegalArgumentException("Cannot be default");
}
   }