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

The following examples show how to use java.lang.reflect.Method#isBridge() . 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: mybatis   File: Reflector.java    License: Apache License 2.0 6 votes vote down vote up
private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
  for (Method currentMethod : methods) {
    if (!currentMethod.isBridge()) {
        //取得签名
      String signature = getSignature(currentMethod);
      // check to see if the method is already known
      // if it is known, then an extended class must have
      // overridden a method
      if (!uniqueMethods.containsKey(signature)) {
        if (canAccessPrivateMethods()) {
          try {
            currentMethod.setAccessible(true);
          } catch (Exception e) {
            // Ignored. This is only a final precaution, nothing we can do.
          }
        }

        uniqueMethods.put(signature, currentMethod);
      }
    }
  }
}
 
Example 2
public void parse() {
  String resource = type.toString();
  if (!configuration.isResourceLoaded(resource)) {
    loadXmlResource();
    configuration.addLoadedResource(resource);
    assistant.setCurrentNamespace(type.getName());
    parseCache();
    parseCacheRef();
    Method[] methods = type.getMethods();
    for (Method method : methods) {
      try {
        // issue #237
        if (!method.isBridge()) {
          parseStatement(method);
        }
      } catch (IncompleteElementException e) {
        configuration.addIncompleteMethod(new MethodResolver(this, method));
      }
    }
  }
  parsePendingMethods();
}
 
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: gimBUS   File: Cache.java    License: MIT License 6 votes vote down vote up
/**
 * Scans single level of the subscriber class, finds any method annotated with the @Subscribe annotation,
 * builds a Map for cache.
 */
@NonNull
static Map<Class<?>, EventHandlersCacheItem> scanForEventHandlers(@NonNull final Class<?> subscriberClass) {
    //NOTE this Map is created once and never modified afterwards. It will be read in many threads later, no synchronisation.
    //I think it is safe to use the HashMap, the ConcurrentHashMap is too heavy.
    Map<Class<?>, EventHandlersCacheItem> eventHandlers = new HashMap<>();

    for (Method method : subscriberClass.getDeclaredMethods()) {
        if (method.isBridge()) {
            continue;
        }
        Subscribe annotation = method.getAnnotation(Subscribe.class);
        if (annotation != null) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length != 1) {
                throw new IllegalStateException("Method " + method + " has @Subscribe annotation but requires "
                        + parameterTypes.length + " arguments. Method must require a single argument.");
            }
            Class<?> eventType = parameterTypes[0];
            eventHandlers.put(eventType, new EventHandlersCacheItem(method, Dispatcher.getDispatchingMethod(annotation), eventHandlers.get(eventType)));
        }
    }

    return eventHandlers;
}
 
Example 5
Source Project: tinybus   File: ObjectsMeta.java    License: Apache License 2.0 5 votes vote down vote up
public ObjectsMeta(Object obj) {
	final Method[] methods = obj.getClass().getMethods();
	
	Class<?>[] params;
	SubscriberCallback callback;
	Subscribe ann;
	for (Method method : methods) {
		if (method.isBridge() || method.isSynthetic()) {
			continue;
		}
		
		ann = method.getAnnotation(Subscribe.class);
		if (ann != null) {
			params = method.getParameterTypes();
			callback = mEventCallbacks.put(params[0], new SubscriberCallback(method, ann));
			if (callback != null) {
				throw new IllegalArgumentException("Only one @Subscriber can be defined "
						+ "for one event type in the same class. Event type: " 
						+ params[0] + ". Class: " + obj.getClass());
			}
			
		} else if (method.isAnnotationPresent(Produce.class)) {
			if (mProducerCallbacks == null) {
				mProducerCallbacks = new HashMap<Class<? extends Object>, Method>();
			}
			mProducerCallbacks.put(method.getReturnType(), method);
		}
	}
}
 
Example 6
private void visitMethods(Class<?> type) {
    for(Method method : type.getDeclaredMethods()) {
        if(!method.isSynthetic() && !method.isBridge() && filter.test(method)) {
            map.merge(new Signature(method), method, (ma, mb) -> {
                // Figure out which method overrides the other
                final Class<?> ta = ma.getDeclaringClass();
                final Class<?> tb = mb.getDeclaringClass();

                // If one method is declared in a class and the other is declared
                // in an interface, the class method always wins.
                if(!ta.isInterface() && tb.isInterface()) return ma;
                if(!tb.isInterface() && ta.isInterface()) return mb;

                // If one method is a default (interface) method, and the other
                // one isn't, keep the default one (the other method must be
                // a normal interface method).
                if(ma.isDefault() && !mb.isDefault()) return ma;
                if(mb.isDefault() && !ma.isDefault()) return mb;

                // If one method's owner is a subtype of the other method's owner,
                // keep the subtype method.
                if(tb.isAssignableFrom(ta)) return ma;
                if(ta.isAssignableFrom(tb)) return mb;

                // If all else fails, keep the method that was encountered first.
                // I'm pretty sure this can only happen with two abstract methods
                // in unrelated interfaces, in which case it probably doesn't
                // matter which one is kept.
                return ma;
            });
        }
    }
}
 
Example 7
Source Project: cxf   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
static boolean isMethodAccepted(Method method, XmlAccessType accessType, boolean acceptSetters) {
    // ignore bridge, static, @XmlTransient methods plus methods declared in Throwable
    if (method.isBridge()
            || Modifier.isStatic(method.getModifiers())
            || method.isAnnotationPresent(XmlTransient.class)
            || method.getDeclaringClass().equals(Throwable.class)
            || "getClass".equals(method.getName())) {
        return false;
    }
    // Allow only public methods if PUBLIC_MEMBER access is requested
    if (accessType == XmlAccessType.PUBLIC_MEMBER && !Modifier.isPublic(method.getModifiers())) {
        return false;
    }
    if (isGetter(method)) {
        // does nothing
    } else if (isSetter(method)) {
        if (!acceptSetters) {
            return false;
        }
    } else {
        // we accept only getters and setters
        return false;
    }
    // let JAXB annotations decide if NONE or FIELD access is requested
    if (accessType == XmlAccessType.NONE || accessType == XmlAccessType.FIELD) {
        return JAXBContextInitializer.checkJaxbAnnotation(method.getAnnotations());
    }
    // method accepted
    return true;
}
 
Example 8
private Method getIdMethod(Class<?> clazz) {
    Method idMethod = null;
    // Get all public declared methods on the class. According to spec, @Id should only be
    // applied to fields and property get methods
    Method[] methods = clazz.getMethods();
    Id idAnnotation = null;
    for (Method method : methods) {
        idAnnotation = method.getAnnotation(Id.class);
        if (idAnnotation != null && !method.isBridge()) {
            idMethod = method;
            break;
        }
    }
    return idMethod;
}
 
Example 9
Source Project: onetwo   File: ReflectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Method findMethod(boolean ignoreIfNotfound, Class<?> objClass, String name, Class<?>... paramTypes) {
	try {
		Class<?> searchType = objClass;
		while (!Object.class.equals(searchType) && searchType != null) {
			Method[] methods = (searchType.isInterface() ? searchType
					.getMethods() : searchType.getDeclaredMethods());
			for (int i = 0; i < methods.length; i++) {
				Method method = methods[i];
				// System.out.println("====>>>method:"+method+" parent: " +
				// method.isBridge());
				// if (name.equals(method.getName()) && (paramTypes == null
				// || Arrays.equals(paramTypes,
				// method.getParameterTypes()))) {
				if (!method.isBridge() && name.equals(method.getName()) && (isEmpty(paramTypes) || matchParameterTypes(paramTypes, method.getParameterTypes()))) {
					// System.out.println("====>>>method match");
					return method;
				}
			}
			searchType = searchType.getSuperclass();
		}
	} catch (Exception e) {
		if (ignoreIfNotfound)
			return null;
		throw new RuntimeException("can not find the method : [class=" + objClass + ", methodName=" + name + ", paramTypes=" + paramTypes + "]");
	}
	if (ignoreIfNotfound)
		return null;
	throw new RuntimeException("can not find the method : [class=" + objClass + ", methodName=" + name + ", paramTypes=" + paramTypes + "]");
}
 
Example 10
Source Project: beam   File: UdfImpl.java    License: Apache License 2.0 5 votes vote down vote up
static Method findMethod(Class<?> clazz, String name) {
  for (Method method : clazz.getMethods()) {
    if (method.getName().equals(name) && !method.isBridge()) {
      return method;
    }
  }
  return null;
}
 
Example 11
/**
 * Find the original method for the supplied {@link Method bridge Method}.
 * <p>It is safe to call this method passing in a non-bridge {@link Method} instance.
 * In such a case, the supplied {@link Method} instance is returned directly to the caller.
 * Callers are <strong>not</strong> required to check for bridging before calling this method.
 * @param bridgeMethod the method to introspect
 * @return the original method (either the bridged method or the passed-in method
 * if no more specific one could be found)
 */
public static Method findBridgedMethod(Method bridgeMethod) {
	if (bridgeMethod == null || !bridgeMethod.isBridge()) {
		return bridgeMethod;
	}
	// Gather all methods with matching name and parameter size.
	List<Method> candidateMethods = new ArrayList<Method>();
	Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass());
	for (Method candidateMethod : methods) {
		if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) {
			candidateMethods.add(candidateMethod);
		}
	}
	// Now perform simple quick check.
	if (candidateMethods.size() == 1) {
		return candidateMethods.get(0);
	}
	// Search for candidate match.
	Method bridgedMethod = searchCandidates(candidateMethods, bridgeMethod);
	if (bridgedMethod != null) {
		// Bridged method found...
		return bridgedMethod;
	}
	else {
		// A bridge method was passed in but we couldn't find the bridged method.
		// Let's proceed with the passed-in method and hope for the best...
		return bridgeMethod;
	}
}
 
Example 12
Source Project: flow   File: AbstractNodeTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void assertMethodsReturnType(Class<? extends Node<?>> clazz,
        Set<String> ignore) {
    for (Method method : clazz.getMethods()) {
        if (method.getDeclaringClass().equals(Object.class)) {
            continue;
        }
        if (!Modifier.isPublic(method.getModifiers())) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        if (method.isBridge()) {
            continue;
        }
        if (method.getName().startsWith("get")
                || method.getName().startsWith("has")
                || method.getName().startsWith("is")
                || ignore.contains(method.getName())) {
            // Ignore
        } else {
            // Setters and such
            Type returnType = GenericTypeReflector
                    .getExactReturnType(method, clazz);
            Assert.assertEquals(
                    "Method " + method.getName()
                            + " has invalid return type",
                    clazz, returnType);
        }
    }
}
 
Example 13
Source Project: quarkus-http   File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Object type for which the {@link Encoder} can be used.
 */
public static Class<?> getDecoderType(Class<? extends Decoder> clazz) {
    Method[] methods = clazz.getMethods();
    for (Method m : methods) {
        if ("decode".equals(m.getName()) && !m.isBridge()) {
            return m.getReturnType();
        }
    }
    throw JsrWebSocketMessages.MESSAGES.couldNotDetermineDecoderTypeFor(clazz);
}
 
Example 14
/**
 * Invokes the first accessible method defined on the receiver'c class with the given name and
 * a parameter list compatible to the given arguments.
 * 
 * @param receiver the method call receiver, not <code>null</code>
 * @param methodName the method name, not <code>null</code>
 * @param args the arguments for the method invocation
 * @return the result of the method invocation. <code>null</code> if the method was of type void.
 * 
 * @throws SecurityException see {@link Class#getMethod(String, Class...)}
 * @throws NoSuchMethodException see {@link Class#getMethod(String, Class...)}
 * @throws IllegalAccessException see {@link Method#invoke(Object, Object...)}
 * @throws IllegalArgumentException see {@link Method#invoke(Object, Object...)}
 * @throws InvocationTargetException see {@link Method#invoke(Object, Object...)}
 */
/* @Nullable */
public Object invoke(Object receiver, String methodName, /* @Nullable */ Object...args) throws SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
	Preconditions.checkNotNull(receiver,"receiver");
	Preconditions.checkNotNull(methodName,"methodName");
	final Object[] arguments = args==null ? new Object[]{null}:args;
	
	Class<? extends Object> clazz = receiver.getClass();
	Method compatible = null;
	do {
		for (Method candidate : clazz.getDeclaredMethods()) {
			if (candidate != null && !candidate.isBridge() && isCompatible(candidate, methodName, arguments)) {
				if (compatible != null) 
					throw new IllegalStateException("Ambiguous methods to invoke. Both "+compatible+" and  "+candidate+" would be compatible choices.");
				compatible = candidate;
			}
		}
	} while(compatible == null && (clazz = clazz.getSuperclass()) != null);
	if (compatible != null) {
		if (!compatible.isAccessible())
			compatible.setAccessible(true);
		return compatible.invoke(receiver, arguments);
	}
	// not found provoke method not found exception
	Class<?>[] paramTypes = new Class<?>[arguments.length];
	for (int i = 0; i< arguments.length ; i++) {
		paramTypes[i] = arguments[i] == null ? Object.class : arguments[i].getClass();
	}
	Method method = receiver.getClass().getMethod(methodName, paramTypes);
	return method.invoke(receiver, arguments);
}
 
Example 15
public boolean isBridgeMethod(Method method) {
    return method.isBridge();
}
 
Example 16
static public List<Method> getMethods(Class c, int arity, String name, boolean getStatics){
    Method[] allmethods = c.getMethods();
    ArrayList methods = new ArrayList();
    ArrayList bridgeMethods = new ArrayList();
    for(int i = 0; i < allmethods.length; i++)
        {
            Method method = allmethods[i];
            if(name.equals(method.getName())
               && Modifier.isStatic(method.getModifiers()) == getStatics
               && method.getParameterTypes().length == arity)
                {
                    try
                        {
                            if(method.isBridge()
                               && c.getMethod(method.getName(), method.getParameterTypes())
                               .equals(method))
                                bridgeMethods.add(method);
                            else
                                methods.add(method);
                        }
                    catch(NoSuchMethodException e)
                        {
                        }
                }
            //                         && (!method.isBridge()
            //                             || (c == StringBuilder.class &&
            //                                c.getMethod(method.getName(), method.getParameterTypes())
            //                                      .equals(method))))
            //                              {
            //                              methods.add(allmethods[i]);
            //                              }
        }

    if(methods.isEmpty())
        methods.addAll(bridgeMethods);

    if(!getStatics && c.isInterface())
        {
            allmethods = Object.class.getMethods();
            for(int i = 0; i < allmethods.length; i++)
                {
                    if(name.equals(allmethods[i].getName())
                       && Modifier.isStatic(allmethods[i].getModifiers()) == getStatics
                       && allmethods[i].getParameterTypes().length == arity)
                        {
                            methods.add(allmethods[i]);
                        }
                }
        }
    return methods;
}
 
Example 17
public boolean isBridgeMethod(Method method) {
    return method.isBridge();
}
 
Example 18
private boolean isAnnotatedMethod(Method method, String annotationName) {
	return !method.isBridge() && method.getAnnotations().length > 0 &&
			AnnotatedElementUtils.isAnnotated(method, annotationName);
}
 
Example 19
Source Project: dolphin   File: ReflectionUtils.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(Method method) {
	return (!method.isBridge() && method.getDeclaringClass() != Object.class);
}
 
Example 20
private void genInterfaceMethodDecl( StringBuilder sb, Method mi, Class rootType )
{
  if( (mi.isDefault() && !implementsMethod( rootType, mi )) ||
      Modifier.isStatic( mi.getModifiers() ) ||
      mi.isBridge() || mi.isSynthetic() )
  {
    return;
  }
  if( mi.getAnnotation( ExtensionMethod.class ) != null )
  {
    return;
  }
  if( isObjectMethod( mi ) )
  {
    return;
  }

  Class returnType = mi.getReturnType();
  sb.append( "  public " )./*append( getTypeVarList( mi ) ).append( ' ' ).*/append( returnType.getCanonicalName() ).append( ' ' ).append( mi.getName() ).append( "(" );
  Class[] params = mi.getParameterTypes();
  for( int i = 0; i < params.length; i++ )
  {
    Class pi = params[i];
    sb.append( ' ' ).append( pi.getCanonicalName() ).append( " p" ).append( i );
    sb.append( i < params.length - 1 ? ',' : ' ' );
  }
  sb.append( ") {\n" )
    .append( returnType == void.class
             ? "    "
             : "    return " )
    .append( maybeCastReturnType( mi, returnType, rootType ) );
  if( !returnType.isPrimitive() )
  {
    sb.append( RuntimeMethods.class.getTypeName() ).append( ".coerce(" );
  }
  if( !handleField( sb, mi ) )
  {
    handleMethod( sb, mi, params );
  }
  if( !returnType.isPrimitive() )
  {
    sb.append( ", " ).append( mi.getReturnType().getCanonicalName() ).append( ".class);\n" );
  }
  else
  {
    sb.append( ";\n" );
  }
  sb.append( "  }\n" );
}