List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:com.espertech.esper.util.MethodResolver.java
/** * Attempts to find the static or instance method described by the parameters, * or a method of the same name that will accept the same type of * parameters./* www. j a v a2s . co m*/ * @param declaringClass - the class to search for the method * @param methodName - the name of the method * @param paramTypes - the parameter types for the method * @param allowInstance - true to allow instance methods as well, false to allow only static method * @return - the Method object for this method * @throws EngineNoSuchMethodException if the method could not be found */ public static Method resolveMethod(Class declaringClass, String methodName, Class[] paramTypes, boolean allowInstance, boolean[] allowEventBeanType, boolean[] allowEventBeanCollType) throws EngineNoSuchMethodException { // Get all the methods for this class Method[] methods = declaringClass.getMethods(); Method bestMatch = null; int bestConversionCount = -1; // Examine each method, checking if the signature is compatible Method conversionFailedMethod = null; for (Method method : methods) { // Check the modifiers: we only want public and static, if required if (!isPublicAndStatic(method, allowInstance)) { continue; } // Check the name if (!method.getName().equals(methodName)) { continue; } // Check the parameter list int conversionCount = compareParameterTypesAllowContext(method.getParameterTypes(), paramTypes, allowEventBeanType, allowEventBeanCollType, method.getGenericParameterTypes()); // Parameters don't match if (conversionCount == -1) { conversionFailedMethod = method; continue; } // Parameters match exactly if (conversionCount == 0) { bestMatch = method; break; } // No previous match if (bestMatch == null) { bestMatch = method; bestConversionCount = conversionCount; } else { // Current match is better if (conversionCount < bestConversionCount) { bestMatch = method; bestConversionCount = conversionCount; } } } if (bestMatch != null) { logWarnBoxedToPrimitiveType(declaringClass, methodName, bestMatch, paramTypes); return bestMatch; } StringBuilder parameters = new StringBuilder(); if (paramTypes != null && paramTypes.length != 0) { String appendString = ""; for (Object param : paramTypes) { parameters.append(appendString); if (param == null) { parameters.append("(null)"); } else { parameters.append(param.toString()); } appendString = ", "; } } throw new EngineNoSuchMethodException( "Unknown method " + declaringClass.getSimpleName() + '.' + methodName + '(' + parameters + ')', conversionFailedMethod); }
From source file:io.stallion.reflection.PropertyUtils.java
public static List<String> getPropertyNames(Class clazz) throws PropertyException { Method[] methods = clazz.getMethods(); List<String> names = list(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; String name = method.getName(); if (method.getModifiers() == Modifier.PUBLIC && method.getParameterTypes().length == 0 && (name.startsWith("get") || name.startsWith("is")) && containsSetterForGetter(clazz, method)) { String propertyName;/* w w w . java2 s. com*/ if (name.startsWith("get")) propertyName = Character.toLowerCase(name.charAt(3)) + name.substring(4); else propertyName = Character.toLowerCase(name.charAt(2)) + name.substring(3); names.add(propertyName); } } return names; }
From source file:org.paxml.util.ReflectUtils.java
/** * Call a static method. If not found, exception will be thrown. * // www .j av a 2s . c o m * @param className * the class name * @param method * the method name * @param args * the args name * @return the method return value. * */ public static Object callStaticMethod(String className, String method, Object[] args) { if (args == null) { args = new Object[0]; } Class clazz = ReflectUtils.loadClassStrict(className, null); for (Method m : clazz.getMethods()) { if (!m.getName().equals(method)) { continue; } Class[] argTypes = m.getParameterTypes(); if (argTypes.length == args.length) { Object[] actualArgs = new Object[args.length]; for (int i = args.length - 1; i >= 0; i--) { actualArgs[i] = ReflectUtils.coerceType(args[i], argTypes[i]); } try { return m.invoke(null, actualArgs); } catch (Exception e) { throw new PaxmlRuntimeException(e); } } } throw new PaxmlRuntimeException( "No method named '" + method + "' has " + args.length + " parameters from class: " + className); }
From source file:com.astamuse.asta4d.util.annotation.AnnotatedPropertyUtil.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private static AnnotatedPropertyInfoMap retrievePropertiesMap(Class cls) { String cacheKey = cls.getName(); AnnotatedPropertyInfoMap map = propertiesMapCache.get(cacheKey); if (map == null) { List<AnnotatedPropertyInfo> infoList = new LinkedList<>(); Set<String> beanPropertyNameSet = new HashSet<>(); Method[] mtds = cls.getMethods(); for (Method method : mtds) { List<Annotation> annoList = ConvertableAnnotationRetriever .retrieveAnnotationHierarchyList(AnnotatedProperty.class, method.getAnnotations()); if (CollectionUtils.isEmpty(annoList)) { continue; }// www. j a v a2s. c o m AnnotatedPropertyInfo info = new AnnotatedPropertyInfo(); info.setAnnotations(annoList); boolean isGet = false; boolean isSet = false; String propertySuffixe = method.getName(); if (propertySuffixe.startsWith("set")) { propertySuffixe = propertySuffixe.substring(3); isSet = true; } else if (propertySuffixe.startsWith("get")) { propertySuffixe = propertySuffixe.substring(3); isGet = true; } else if (propertySuffixe.startsWith("is")) { propertySuffixe = propertySuffixe.substring(2); isSet = true; } else { String msg = String.format("Method [%s]:[%s] can not be treated as a getter or setter method.", cls.getName(), method.toGenericString()); throw new RuntimeException(msg); } char[] cs = propertySuffixe.toCharArray(); cs[0] = Character.toLowerCase(cs[0]); info.setBeanPropertyName(new String(cs)); AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by String name = ap.name(); if (StringUtils.isEmpty(name)) { name = info.getBeanPropertyName(); } info.setName(name); if (isGet) { info.setGetter(method); info.setType(method.getReturnType()); String setterName = "set" + propertySuffixe; Method setter = null; try { setter = cls.getMethod(setterName, method.getReturnType()); } catch (NoSuchMethodException | SecurityException e) { String msg = "Could not find setter method:[{}({})] in class[{}] for annotated getter:[{}]"; logger.warn(msg, new Object[] { setterName, method.getReturnType().getName(), cls.getName(), method.getName() }); } info.setSetter(setter); } if (isSet) { info.setSetter(method); info.setType(method.getParameterTypes()[0]); String getterName = "get" + propertySuffixe; Method getter = null; try { getter = cls.getMethod(getterName); } catch (NoSuchMethodException | SecurityException e) { String msg = "Could not find getter method:[{}:{}] in class[{}] for annotated setter:[{}]"; logger.warn(msg, new Object[] { getterName, method.getReturnType().getName(), cls.getName(), method.getName() }); } info.setGetter(getter); } infoList.add(info); beanPropertyNameSet.add(info.getBeanPropertyName()); } List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(cls)); Iterator<Field> it = list.iterator(); while (it.hasNext()) { Field f = it.next(); List<Annotation> annoList = ConvertableAnnotationRetriever .retrieveAnnotationHierarchyList(AnnotatedProperty.class, f.getAnnotations()); if (CollectionUtils.isNotEmpty(annoList)) { AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by String beanPropertyName = f.getName(); if (beanPropertyNameSet.contains(beanPropertyName)) { continue; } String name = ap.name(); if (StringUtils.isEmpty(name)) { name = f.getName(); } AnnotatedPropertyInfo info = new AnnotatedPropertyInfo(); info.setAnnotations(annoList); info.setBeanPropertyName(beanPropertyName); info.setName(name); info.setField(f); info.setGetter(null); info.setSetter(null); info.setType(f.getType()); infoList.add(info); } } map = new AnnotatedPropertyInfoMap(infoList); if (Configuration.getConfiguration().isCacheEnable()) { propertiesMapCache.put(cacheKey, map); } } return map; }
From source file:com.github.valdr.thirdparty.spring.AnnotationUtils.java
private static boolean isInterfaceWithAnnotatedMethods(Class<?> iface) { synchronized (annotatedInterfaceCache) { Boolean flag = annotatedInterfaceCache.get(iface); if (flag != null) { return flag; }/* w w w. java 2 s . c o m*/ boolean found = false; for (Method ifcMethod : iface.getMethods()) { if (ifcMethod.getAnnotations().length > 0) { found = true; break; } } annotatedInterfaceCache.put(iface, found); return found; } }
From source file:io.stallion.reflection.PropertyUtils.java
/** * Build a map of direct javabeans properties of the target object. Only read/write properties (ie: those who have * both a getter and a setter) are returned. * @param target the target object from which to get properties names. * @return a Map of String with properties names as key and their values * @throws PropertyException if an error happened while trying to get a property. *///from w w w . j av a2 s.co m public static Map<String, Object> getProperties(Object target, Class<? extends Annotation>... excludeAnnotations) throws PropertyException { Map<String, Object> properties = new HashMap<String, Object>(); Class clazz = target.getClass(); Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; String name = method.getName(); Boolean hasExcludeAnno = false; if (excludeAnnotations.length > 0) { for (Class<? extends Annotation> anno : excludeAnnotations) { if (method.isAnnotationPresent(anno)) { hasExcludeAnno = true; } } } if (hasExcludeAnno) { continue; } if (method.getModifiers() == Modifier.PUBLIC && method.getParameterTypes().length == 0 && (name.startsWith("get") || name.startsWith("is")) && containsSetterForGetter(clazz, method)) { String propertyName; if (name.startsWith("get")) propertyName = Character.toLowerCase(name.charAt(3)) + name.substring(4); else if (name.startsWith("is")) propertyName = Character.toLowerCase(name.charAt(2)) + name.substring(3); else throw new PropertyException( "method '" + name + "' is not a getter, thereof no setter can be found"); try { Object propertyValue = method.invoke(target, (Object[]) null); // casting to (Object[]) b/c of javac 1.5 warning if (propertyValue != null && propertyValue instanceof Properties) { Map propertiesContent = getNestedProperties(propertyName, (Properties) propertyValue); properties.putAll(propertiesContent); } else { properties.put(propertyName, propertyValue); } } catch (IllegalAccessException ex) { throw new PropertyException("cannot set property '" + propertyName + "' - '" + name + "' is null and cannot be auto-filled", ex); } catch (InvocationTargetException ex) { throw new PropertyException("cannot set property '" + propertyName + "' - '" + name + "' is null and cannot be auto-filled", ex); } } // if } // for return properties; }
From source file:ReflectUtil.java
/** * <p>A better (more concise) toString method for annotation types that yields a String * that should look more like the actual usage of the annotation in a class. The String produced * is similar to that produced by calling toString() on the annotation directly, with the * following differences:</p>//from w ww . j av a2 s . c o m * * <ul> * <li>Uses the classes simple name instead of it's fully qualified name.</li> * <li>Only outputs attributes that are set to non-default values.</li> * * <p>If, for some unforseen reason, an exception is thrown within this method it will be * caught and the return value will be {@code ann.toString()}. * * @param ann the annotation to convert to a human readable String * @return a human readable String form of the annotation and it's attributes */ public static String toString(Annotation ann) { try { Class<? extends Annotation> type = ann.annotationType(); StringBuilder builder = new StringBuilder(128); builder.append("@"); builder.append(type.getSimpleName()); boolean appendedAnyParameters = false; Method[] methods = type.getMethods(); for (Method method : methods) { if (!INHERITED_ANNOTATION_METHODS.contains(method.getName())) { Object defaultValue = method.getDefaultValue(); Object actualValue = method.invoke(ann); // If we have arrays, they have to be treated a little differently Object[] defaultArray = null, actualArray = null; if (Object[].class.isAssignableFrom(method.getReturnType())) { defaultArray = (Object[]) defaultValue; actualArray = (Object[]) actualValue; } // Only print an attribute if it isn't set to the default value if ((defaultArray != null && !Arrays.equals(defaultArray, actualArray)) || (defaultArray == null && !actualValue.equals(defaultValue))) { if (appendedAnyParameters) { builder.append(", "); } else { builder.append("("); } builder.append(method.getName()); builder.append("="); if (actualArray != null) { builder.append(Arrays.toString(actualArray)); } else { builder.append(actualValue); } appendedAnyParameters = true; } } } if (appendedAnyParameters) { builder.append(")"); } return builder.toString(); } catch (Exception e) { return ann.toString(); } }
From source file:net.jodah.typetools.TypeResolver.java
/** * Populates the {@code map} with variable/argument pairs for the {@code functionalInterface}. *///from w ww . j a v a 2 s .c o m private static void populateLambdaArgs(Class<?> functionalInterface, final Class<?> lambdaType, Map<TypeVariable<?>, Type> map) { if (GET_CONSTANT_POOL != null) { try { // Find SAM for (Method m : functionalInterface.getMethods()) { if (!m.isDefault() && !Modifier.isStatic(m.getModifiers()) && !m.isBridge()) { // Skip methods that override Object.class Method objectMethod = OBJECT_METHODS.get(m.getName()); if (objectMethod != null && Arrays.equals(m.getTypeParameters(), objectMethod.getTypeParameters())) continue; // Get functional interface's type params Type returnTypeVar = m.getGenericReturnType(); Type[] paramTypeVars = m.getGenericParameterTypes(); // Get lambda's type arguments ConstantPool constantPool = (ConstantPool) GET_CONSTANT_POOL.invoke(lambdaType); String[] methodRefInfo = constantPool.getMemberRefInfoAt( constantPool.getSize() - resolveMethodRefOffset(constantPool, lambdaType)); // Skip auto boxing methods if (methodRefInfo[1].equals("valueOf") && constantPool.getSize() > 22) { try { methodRefInfo = constantPool.getMemberRefInfoAt(constantPool.getSize() - resolveAutoboxedMethodRefOffset(constantPool, lambdaType)); } catch (MethodRefOffsetResolutionFailed ignore) { } } if (returnTypeVar instanceof TypeVariable) { Class<?> returnType = TypeDescriptor.getReturnType(methodRefInfo[2]) .getType(lambdaType.getClassLoader()); if (!returnType.equals(Void.class)) map.put((TypeVariable<?>) returnTypeVar, returnType); } TypeDescriptor[] arguments = TypeDescriptor.getArgumentTypes(methodRefInfo[2]); // Handle arbitrary object instance method references int paramOffset = 0; if (paramTypeVars[0] instanceof TypeVariable && paramTypeVars.length == arguments.length + 1) { Class<?> instanceType = TypeDescriptor.getObjectType(methodRefInfo[0]) .getType(lambdaType.getClassLoader()); map.put((TypeVariable<?>) paramTypeVars[0], instanceType); paramOffset = 1; } // Handle local final variables from context that are passed as arguments. int argOffset = 0; if (paramTypeVars.length < arguments.length) { argOffset = arguments.length - paramTypeVars.length; } for (int i = 0; i + argOffset < arguments.length; i++) { if (paramTypeVars[i] instanceof TypeVariable) { map.put((TypeVariable<?>) paramTypeVars[i + paramOffset], arguments[i + argOffset].getType(lambdaType.getClassLoader())); } } break; } } } catch (Exception ignore) { } } }
From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java
public static Method getMethod(Class<?> cl, String method) { for (Method m : cl.getMethods()) { if (m.getName().equals(method)) { return m; }/* ww w .j a va 2 s . c o m*/ } return null; }
From source file:bammerbom.ultimatecore.bukkit.resources.utils.BossbarUtil.java
public static Method getMethod(Class<?> cl, String method, Integer args) { for (Method m : cl.getMethods()) { if ((m.getName().equals(method)) && (args.equals(new Integer(m.getParameterTypes().length)))) { return m; }//from w w w.j ava2s .co m } return null; }