List of usage examples for java.lang.reflect Method getParameterTypes
@Override
public Class<?>[] getParameterTypes()
From source file:de.codesourcery.eve.apiclient.parsers.HttpAPIClientTest.java
private static Method findParserMethod(String name, Class<?>... args) throws Exception { try {/*from w w w. j av a2 s .c o m*/ return AbstractResponseParser.class.getDeclaredMethod(name, args); } catch (Exception e) { try { return AbstractResponseParser.class.getMethod(name, args); } catch (Exception e2) { for (Method m : AbstractResponseParser.class.getMethods()) { if (!m.getName().equals(name)) { System.out.println("# Name mismatch: " + m); continue; } if (!ObjectUtils.equals(m.getParameterTypes(), args)) { System.out.println("# Param mismatch: " + m); continue; } final int modifiers = m.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers) || Modifier.isFinal(modifiers)) { System.out.println("# Modifier mismatch: " + m); continue; } return m; } throw e2; } } }
From source file:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java
static public DataAttributes encode(Object data) throws DataConvertException { setLangridConverter();/*w w w.j a va 2 s. c o m*/ logger.debug("##### encode #####"); try { DataAttributes attr = new DataAttributes(); for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(data)) { if (PropertyUtils.isReadable(data, descriptor.getName())) { if (descriptor.getName().equalsIgnoreCase("supportedLanguages")) { //supportedLanguages attr.setAttribute(descriptor.getName(), (String) converter.lookup(descriptor.getPropertyType()).convert(String.class, PropertyUtils.getProperty(data, descriptor.getName()))); continue; } else if (descriptor.getName().equalsIgnoreCase("instance")) { // // continue; } else if (descriptor.getName().equalsIgnoreCase("wsdl")) { // // continue; } else if (descriptor.getName().equalsIgnoreCase("interfaceDefinitions")) { // // ServiceType type = (ServiceType) data; Map<String, ServiceInterfaceDefinition> map = new HashMap<String, ServiceInterfaceDefinition>(); map = type.getInterfaceDefinitions(); String str = ""; try { for (ServiceInterfaceDefinition s : map.values()) { str = str + "ProtocolId=" + s.getProtocolId() + "\n"; str = str + "Definition=" + Base64.encode(StreamUtil.readAsBytes(s.getDefinition().getBinaryStream())) + "\n"; str = str + "###ServiceInterfaceDefinition###\n"; } } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } attr.setAttribute("interfaceDefinition_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("allowedAppProvision")) { Service s = (Service) data; String value = ""; for (String str : s.getAllowedAppProvision()) { value = value + str + "\n"; } attr.setAttribute("allowedAppProvision", value); continue; } else if (descriptor.getName().equalsIgnoreCase("allowedUse")) { Service s = (Service) data; String value = ""; for (String str : s.getAllowedUse()) { value = value + str + "\n"; } attr.setAttribute("allowedUse", value); continue; } else if (descriptor.getName().equalsIgnoreCase("supportedDomains")) { Grid g = (Grid) data; List<Domain> list = g.getSupportedDomains(); String value = ""; for (Domain d : list) { value = value + d.getDomainId() + "\n"; } attr.setAttribute("supportedDomain_list", value); continue; } else if (descriptor.getName().equalsIgnoreCase("partnerServiceNamespaceURIs")) { //partnerServiceNamespaceURIs BPELService s = (BPELService) data; List<String> list = s.getPartnerServiceNamespaceURIs(); String value = ""; for (String str : list) { value = value + str + "\n"; } attr.setAttribute("partnerServiceNamespaceURI_list", value); continue; } else if (descriptor.getName().equalsIgnoreCase("serviceDeployments")) { //ServiceDeployment Service s = (Service) data; String str = ""; for (ServiceDeployment sd : s.getServiceDeployments()) { str = str + "GridId=" + sd.getGridId() + "\n"; str = str + "ServiceId=" + sd.getServiceId() + "\n"; str = str + "NodeId=" + sd.getNodeId() + "\n"; str = str + "ServicePath=" + sd.getServicePath() + "\n"; str = str + "Enabled=" + String.valueOf(sd.isEnabled()) + "\n"; str = str + "CreateTime=" + String.valueOf(sd.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "UpdateTime=" + String.valueOf(sd.getUpdatedDateTime().getTimeInMillis()) + "\n"; if (sd.getDisabledByErrorDate() != null) { str = str + "ErrorDate=" + String.valueOf(sd.getDisabledByErrorDate().getTimeInMillis()) + "\n"; } if (sd.getDeployedDateTime() != null) { str = str + "DeployedTime=" + String.valueOf(sd.getDeployedDateTime().getTimeInMillis()) + "\n"; } str = str + "###ServiceDeployment###\n"; } attr.setAttribute("deployment_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("serviceEndpoints")) { //ServiceEndpoint StringBuilder str = new StringBuilder(); Service s = (Service) data; for (ServiceEndpoint se : s.getServiceEndpoints()) { str.append("GridId=" + se.getGridId() + "\n"); str.append("ProtocolId=" + se.getProtocolId() + "\n"); str.append("ServiceId=" + se.getServiceId() + "\n"); str.append("Enabled=" + String.valueOf(se.isEnabled()) + "\n"); str.append("Url=" + se.getUrl().toString() + "\n"); str.append("AuthUserName=" + se.getAuthUserName() + "\n"); str.append("AuthPassword=" + se.getAuthPassword() + "\n"); str.append("DisableReason=" + se.getDisableReason() + "\n"); str.append("CreateTime=" + String.valueOf(se.getCreatedDateTime().getTimeInMillis()) + "\n"); str.append("UpdateTime=" + String.valueOf(se.getUpdatedDateTime().getTimeInMillis()) + "\n"); if (se.getDisabledByErrorDate() != null) { str.append("ErrorDate=" + String.valueOf(se.getDisabledByErrorDate().getTimeInMillis()) + "\n"); } str.append("###ServiceEndpoint###\n"); } attr.setAttribute("endpoint_list", str.toString()); continue; } else if (descriptor.getName().equalsIgnoreCase("invocations")) { //Invocation String str = ""; Service s = (Service) data; for (Invocation in : s.getInvocations()) { str = str + "InvocationName=" + in.getInvocationName() + "\n"; str = str + "OwnerServiceGridId=" + in.getOwnerServiceGridId() + "\n"; str = str + "OwnerServiceId=" + in.getOwnerServiceId() + "\n"; str = str + "ServiceGridId=" + in.getServiceGridId() + "\n"; str = str + "ServiceId=" + in.getServiceId() + "\n"; str = str + "ServiceName=" + in.getServiceName() + "\n"; str = str + "CreateTime=" + String.valueOf(in.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "UpdateTime=" + String.valueOf(in.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Invocation###\n"; } attr.setAttribute("invocations_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("metaAttributes")) { //metaAttributes String str = ""; if (data.getClass().getName().endsWith("ResourceType")) { ResourceType r = (ResourceType) data; for (ResourceMetaAttribute a : r.getMetaAttributes().values()) { str = str + "DomainId=" + a.getDomainId() + "\n"; str = str + "AttributeId=" + a.getAttributeId() + "\n"; str = str + "###MetaAttribute###\n"; } } else if (data.getClass().getName().endsWith("ServiceType")) { ServiceType s = (ServiceType) data; for (ServiceMetaAttribute a : s.getMetaAttributes().values()) { str = str + "DomainId=" + a.getDomainId() + "\n"; str = str + "AttributeId=" + a.getAttributeId() + "\n"; str = str + "###MetaAttribute###\n"; } } else { logger.info("metaAttributes : " + data.getClass().getName()); } attr.setAttribute("metaAttribute_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("attributes")) { //attribute String str = ""; if (data.getClass().getName().endsWith("User")) { User u = (User) data; for (UserAttribute a : u.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getUserId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Service")) { Service s = (Service) data; for (ServiceAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getServiceId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Node")) { Node s = (Node) data; for (NodeAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getNodeId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Grid")) { Grid s = (Grid) data; for (GridAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Resource")) { Resource s = (Resource) data; for (ResourceAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getResourceId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } attr.setAttribute("attribute_list", str); continue; } else if (data instanceof Service && (descriptor.getName().equals("alternateServiceId") || descriptor.getName().equals("useAlternateServices"))) { // // continue; } //Read OK if (data instanceof BPELService && descriptor.getName().equals("transferExecution")) { // ignore } else { attr.setAttribute(descriptor.getName(), BeanUtils.getProperty(data, descriptor.getName())); } } else if (descriptor.getPropertyType().isArray()) { logger.debug("name : " + descriptor.getName() + " isArray"); // // attr.setAttribute(descriptor.getName(), (String) converter.lookup(descriptor.getPropertyType()) .convert(String.class, PropertyUtils.getProperty(data, descriptor.getName()))); } else { logger.debug("Name : " + descriptor.getName()); for (Method m : data.getClass().getMethods()) { if (m.getName().equalsIgnoreCase("get" + descriptor.getName()) || m.getName().equalsIgnoreCase("is" + descriptor.getName())) { if (m.getParameterTypes().length != 0) { // // logger.debug("class : " + data.getClass().getName()); logger.debug("?:Skip"); break; } else { // // logger.debug("value : " + m.invoke(data)); } attr.setAttribute(descriptor.getName(), m.invoke(data).toString()); break; } } } } return attr; } catch (InvocationTargetException e) { throw new DataConvertException(e); } catch (IllegalArgumentException e) { throw new DataConvertException(e); } catch (IllegalAccessException e) { throw new DataConvertException(e); } catch (NoSuchMethodException e) { throw new DataConvertException(e); } }
From source file:com.dianping.resource.io.util.ReflectionUtils.java
/** * Get the unique set of declared methods on the leaf class and all superclasses. Leaf * class methods are included first and while traversing the superclass hierarchy any methods found * with signatures matching a method already included are filtered out. *//*from w ww . j ava 2 s . c o m*/ public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // Is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); }
From source file:ca.sqlpower.testutil.TestUtils.java
/** * Returns the set of property names which have both a getter and a setter * method and are annotated to be persisted through the {@link SPPersister} * classes.//from www. ja v a 2 s .com * * @param objectUnderTest * The object that contains the persistable properties we want to * find. * @param includeTransient * If true the properties marked as transient will also be * included. If false only the properties that are persisted and * not transient are returned. * @param includeConstructorMutators * If true the properties that have getters but can only be set * through a constructor due to being final will be included. If * false the persisted properties provided must have a setter. */ public static Set<String> findPersistableBeanProperties(SPObject objectUnderTest, boolean includeTransient, boolean includeConstructorMutators) throws Exception { Set<String> getters = new HashSet<String>(); Set<String> setters = new HashSet<String>(); for (Method m : objectUnderTest.getClass().getMethods()) { if (m.getName().equals("getClass")) continue; //skip non-public methods as they are not visible for persisting anyways. if (!Modifier.isPublic(m.getModifiers())) continue; //skip static methods if (Modifier.isStatic(m.getModifiers())) continue; if (m.getName().startsWith("get") || m.getName().startsWith("is")) { Class<?> parentClass = objectUnderTest.getClass(); boolean accessor = false; boolean ignored = false; boolean isTransient = false; parentClass.getMethod(m.getName(), m.getParameterTypes());//test while (parentClass != null) { Method parentMethod; try { parentMethod = parentClass.getMethod(m.getName(), m.getParameterTypes()); } catch (NoSuchMethodException e) { parentClass = parentClass.getSuperclass(); continue; } if (parentMethod.getAnnotation(Accessor.class) != null) { accessor = true; if (parentMethod.getAnnotation(Transient.class) != null) { isTransient = true; } break; } else if (parentMethod.getAnnotation(NonProperty.class) != null || parentMethod.getAnnotation(NonBound.class) != null) { ignored = true; break; } parentClass = parentClass.getSuperclass(); } if (accessor) { if (includeTransient || !isTransient) { if (m.getName().startsWith("get")) { getters.add(m.getName().substring(3)); } else if (m.getName().startsWith("is")) { getters.add(m.getName().substring(2)); } } } else if (ignored) { //ignored so skip } else { fail("The method " + m.getName() + " of " + objectUnderTest.toString() + " is a getter that is not annotated " + "to be an accessor or transient. The exiting annotations are " + Arrays.toString(m.getAnnotations())); } } else if (m.getName().startsWith("set")) { if (m.getAnnotation(Mutator.class) != null) { if ((includeTransient || m.getAnnotation(Transient.class) == null) && (includeConstructorMutators || !m.getAnnotation(Mutator.class).constructorMutator())) { setters.add(m.getName().substring(3)); } } else if (m.getAnnotation(NonProperty.class) != null || m.getAnnotation(NonBound.class) != null) { //ignored so skip and pass } else { fail("The method " + m.getName() + " is a setter that is not annotated " + "to be a mutator or transient."); } } } Set<String> beanNames = new HashSet<String>(); for (String beanName : getters) { if (setters.contains(beanName)) { String firstLetter = new String(new char[] { beanName.charAt(0) }); beanNames.add(beanName.replaceFirst(firstLetter, firstLetter.toLowerCase())); } } return beanNames; }
From source file:io.coala.json.DynaBean.java
/** * @param referenceType// w w w . j a va2s. com * @param <S> * @param <T> * @return */ static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType, final Properties... imports) { return new JsonDeserializer<T>() { @Override public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt, final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { return deserialize(jp, ctxt); } @Override public T deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; // if( Wrapper.class.isAssignableFrom( resultType ) ) // { // // FIXME // LOG.trace( "deser wrapper intf of {}", jp.getText() ); // return (T) Wrapper.Util.valueOf( jp.getText(), // resultType.asSubclass( Wrapper.class ) ); // } if (Config.class.isAssignableFrom(resultType)) { final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() { }); final Iterator<Entry<String, Object>> it = entries.entrySet().iterator(); for (Entry<String, Object> next = null; it.hasNext(); next = it.next()) if (next != null && next.getValue() == null) { LOG.trace("Ignoring null value: {}", next); it.remove(); } return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries)); } // else if (Config.class.isAssignableFrom(resultType)) // throw new JsonGenerationException( // "Config does not extend "+Mutable.class.getName()+" required for deserialization: " // + Arrays.asList(resultType // .getInterfaces())); // can't parse directly to interface type final DynaBean bean = new DynaBean(); final TreeNode tree = jp.readValueAsTree(); // override attributes as defined in interface getters final Set<String> attributes = new HashSet<>(); for (Method method : resultType.getMethods()) { if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0) continue; final String attribute = method.getName(); if (attribute.equals("toString") || attribute.equals("hashCode")) continue; attributes.add(attribute); final TreeNode value = tree.get(attribute);// bean.any().get(attributeName); if (value == null) continue; bean.set(method.getName(), om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports))); } if (tree.isObject()) { // keep superfluous properties as TreeNodes, just in case final Iterator<String> fieldNames = tree.fieldNames(); while (fieldNames.hasNext()) { final String fieldName = fieldNames.next(); if (!attributes.contains(fieldName)) bean.set(fieldName, tree.get(fieldName)); } } else if (tree.isValueNode()) { for (Class<?> type : resultType.getInterfaces()) for (Method method : type.getDeclaredMethods()) { // LOG.trace( "Scanning {}", method ); if (method.isAnnotationPresent(JsonProperty.class)) { final String property = method.getAnnotation(JsonProperty.class).value(); // LOG.trace( "Setting {}: {}", property, // ((ValueNode) tree).textValue() ); bean.set(property, ((ValueNode) tree).textValue()); } } } else throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType, tree.getClass()); return DynaBean.proxyOf(om, resultType, bean, imports); } }; }
From source file:eu.crisis_economics.abm.model.ModelUtils.java
public static List<GetterSetterPair> parameters(final Object of, final Class<?> paramType) { final List<GetterSetterPair> result = new ArrayList<GetterSetterPair>(); final Class<?> parentType = of.getClass(); for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch .getSuperclass()) {// ww w . j a v a2s . c o m final Map<String, Method> methodNames = new HashMap<String, Method>(); final Method[] allCalleeMethods = typeToSearch.getDeclaredMethods(); for (final Method method : allCalleeMethods) { final String name = method.getName(); if (name.startsWith("get") && ClassUtils.isAssignable(paramType, method.getReturnType(), true)) methodNames.put(method.getName(), method); else if (name.startsWith("set") && method.getParameterTypes().length == 1 && ClassUtils.isAssignable(paramType, method.getParameterTypes()[0], true)) methodNames.put(method.getName(), method); else continue; final String complement; if (name.startsWith("get")) { complement = "set" + name.substring(3); if (methodNames.containsKey(complement)) result.add(new GetterSetterPair(method, methodNames.get(complement), of)); } else if (name.startsWith("set")) { complement = "get" + name.substring(3); if (methodNames.containsKey(complement)) result.add(new GetterSetterPair(methodNames.get(complement), method, of)); } } } // Search for any ComponentConfiguration fields in the specified object: for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch .getSuperclass()) { for (Field field : typeToSearch.getDeclaredFields()) { if (!ComponentConfiguration.class.isAssignableFrom(field.getType())) continue; field.setAccessible(true); final Object instance; try { instance = field.get(of); } catch (final IllegalArgumentException e) { continue; // Not found } catch (final IllegalAccessException e) { continue; // Not found } if (instance != null) { final List<GetterSetterPair> subResult = parameters(instance, paramType); // Descend into fields if (subResult != null && !subResult.isEmpty()) result.addAll(subResult); else continue; } } } return result; }
From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java
/** * ???//from w w w .j a va 2 s . c o m * * @param methodDescriptor * ?? * @param object * ?? * @param parameters * ?? * @return ? * @throws Exception */ @SuppressWarnings("unchecked") private static Object invokeMethod(MethodDescriptor methodDescriptor, Object object, Object[] parameters) throws Exception { Method method = methodDescriptor.getMethod(); Class<?>[] parameterTypes = method.getParameterTypes(); int[] argIndexs = methodDescriptor.getArgIndexs(); Object[] realArgs = new Object[argIndexs.length]; for (int i = 0; i < argIndexs.length; i++) { Object arg = parameters[argIndexs[i]]; if (arg != null) { Class<?> defType = parameterTypes[i]; Class<?> argType = ProxyBeanUtils.getProxyTargetType(arg.getClass()); if (!defType.isAssignableFrom(argType)) { if (Number.class.isAssignableFrom(defType) && Number.class.isAssignableFrom(argType)) { arg = NumberUtils.convertNumberToTargetClass((Number) arg, (Class<? extends Number>) defType); } else if (isSimpleType(defType) || isSimpleType(argType)) { arg = ConvertUtils.convert(arg, defType); } } } realArgs[i] = arg; } return method.invoke(object, realArgs); }
From source file:com.xiongyingqi.util.ReflectionUtils.java
/** * Get the unique set of declared methods on the leaf class and all superclasses. Leaf * class methods are included first and while traversing the superclass hierarchy any methods found * with signatures matching a method already included are filtered out. *//* ww w. j a v a 2 s .c o m*/ public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); }
From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java
/** * Get the unique set of declared methods on the leaf class and all superclasses. Leaf * class methods are included first and while traversing the superclass hierarchy any methods found * with signatures matching a method already included are filtered out. *//*from w w w.j a v a 2 s .c o m*/ public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // Is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); }
From source file:com.mawujun.utils.AnnotationUtils.java
/** * Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method}, * traversing its super methods if no annotation can be found on the given method itself. * <p>Annotations on methods are not inherited by default, so we need to handle this explicitly. * @param method the method to look for annotations on * @param annotationType the annotation class to look for * @return the annotation found, or {@code null} if none found *///from w ww. j a v a 2 s .c o m public static <A extends Annotation> A findAnnotation(Method method, Class<A> annotationType) { A annotation = getAnnotation(method, annotationType); Class<?> cl = method.getDeclaringClass(); if (annotation == null) { annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces()); } while (annotation == null) { cl = cl.getSuperclass(); if (cl == null || cl == Object.class) { break; } try { Method equivalentMethod = cl.getDeclaredMethod(method.getName(), method.getParameterTypes()); annotation = getAnnotation(equivalentMethod, annotationType); } catch (NoSuchMethodException ex) { // No equivalent method found } if (annotation == null) { annotation = searchOnInterfaces(method, annotationType, cl.getInterfaces()); } } return annotation; }