Java Code Examples for org.apache.commons.lang3.ClassUtils

The following examples show how to use org.apache.commons.lang3.ClassUtils. 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: tcases   Source File: SystemInputResources.java    License: MIT License 6 votes vote down vote up
/**
 * Returns the {@link SystemInputDef} defined by the given JSON resource.
 */
public SystemInputDef readJson( String resource)
  {
  SystemInputDef  systemInputDef  = null;
  InputStream     stream          = null;
  
  stream = class_.getResourceAsStream( resource);
  if( stream == null)
    {
    throw
      new RuntimeException
      ( "Can't find resource=" + ClassUtils.getPackageName( class_) + "." + resource);
    }

  try( SystemInputJsonReader reader = new SystemInputJsonReader( stream))
    {
    systemInputDef = reader.getSystemInputDef();
    }

  return systemInputDef;
  }
 
Example 2
Source Project: astor   Source File: MemberUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the number of steps required to promote a primitive number to another
 * type.
 * @param srcClass the (primitive) source class
 * @param destClass the (primitive) destination class
 * @return The cost of promoting the primitive
 */
private static float getPrimitivePromotionCost(final Class<?> srcClass, final Class<?> destClass) {
    float cost = 0.0f;
    Class<?> cls = srcClass;
    if (!cls.isPrimitive()) {
        // slight unwrapping penalty
        cost += 0.1f;
        cls = ClassUtils.wrapperToPrimitive(cls);
    }
    for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
        if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
            cost += 0.1f;
            if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
                cls = ORDERED_PRIMITIVE_TYPES[i + 1];
            }
        }
    }
    return cost;
}
 
Example 3
Source Project: cuba   Source File: KryoSerialization.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object read(Kryo kryo, Input input, Class type) {
    try {
        ObjectMap graphContext = kryo.getGraphContext();
        ObjectInputStream objectStream = (ObjectInputStream) graphContext.get(this);
        if (objectStream == null) {
            objectStream = new ObjectInputStream(input) {
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
                    return ClassUtils.getClass(KryoSerialization.class.getClassLoader(), desc.getName());
                }
            };
            graphContext.put(this, objectStream);
        }
        return objectStream.readObject();
    } catch (Exception ex) {
        throw new KryoException("Error during Java deserialization.", ex);
    }
}
 
Example 4
Source Project: fastquery   Source File: Script2Class.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 处理脚本中的冒号表达式
 * @param script 脚本
 * @param method 脚本的所属方法
 * @return 被处理后的脚本
 */
private static String processParam(String script, Method method) {
	List<String> names = TypeUtil.matches(script, Placeholder.COLON_REG);
	for (String paramName : names) {
		String name = paramName.replace(":", "");
		Class<?> oldC = Judge.getParamType(name, method);
		Class<?> newC = ClassUtils.primitiveToWrapper(oldC);
		if(oldC == newC) {
			// 包装类型 如果后面跟着
			script = script.replaceAll(paramName, "(("+newC.getName()+")this.getParameter(\""+name+"\"))");
			
		} else { // 基本类型 -> 包装类型 那么就要解包
			// 加上解包方法
			script = script.replaceAll(paramName, "(("+newC.getName()+")this.getParameter(\""+name+"\"))." + oldC.getName() + "Value()");
		}
	}
	return script;
}
 
Example 5
void init()
{
    List<ExternalSearchProviderFactory> exts = new ArrayList<>();

    if (providersProxy != null) {
        exts.addAll(providersProxy);
        AnnotationAwareOrderComparator.sort(exts);

        for (ExternalSearchProviderFactory fs : exts) {
            log.info("Found external search provider: {}",
                    ClassUtils.getAbbreviatedName(fs.getClass(), 20));
        }
    }

    providers = Collections.unmodifiableList(exts);
}
 
Example 6
Source Project: inception   Source File: EventLoggingListener.java    License: Apache License 2.0 6 votes vote down vote up
void init()
{
    List<EventLoggingAdapter<?>> exts = new ArrayList<>();

    if (adapterProxy != null) {
        exts.addAll(adapterProxy);
        AnnotationAwareOrderComparator.sort(exts);

        for (EventLoggingAdapter<?> fs : exts) {
            log.info("Found event logging adapter: {}",
                    ClassUtils.getAbbreviatedName(fs.getClass(), 20));
        }
    }

    adapters = Collections.unmodifiableList(exts);
}
 
Example 7
Source Project: inception   Source File: ConceptLinkingServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
void init()
{
    List<EntityRankingFeatureGenerator> generators = new ArrayList<>();

    if (featureGeneratorsProxy != null) {
        generators.addAll(featureGeneratorsProxy);
        AnnotationAwareOrderComparator.sort(generators);
    
        for (EntityRankingFeatureGenerator generator : generators) {
            log.info("Found entity ranking feature generator: {}",
                    ClassUtils.getAbbreviatedName(generator.getClass(), 20));
        }
    }

    featureGenerators = unmodifiableList(generators);
}
 
Example 8
Source Project: vjtools   Source File: ExceptionUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 拼装 短异常类名: 异常信息 <-- RootCause的短异常类名: 异常信息
 */
public static String toStringWithRootCause(@Nullable Throwable t) {
	if (t == null) {
		return StringUtils.EMPTY;
	}

	final String clsName = ClassUtils.getShortClassName(t, null);
	final String message = StringUtils.defaultString(t.getMessage());
	Throwable cause = getRootCause(t);

	StringBuilder sb = new StringBuilder(128).append(clsName).append(": ").append(message);
	if (cause != t) {
		sb.append("; <---").append(toStringWithShortName(cause));
	}

	return sb.toString();
}
 
Example 9
Source Project: astor   Source File: MemberUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the number of steps required to promote a primitive number to another
 * type.
 * @param srcClass the (primitive) source class
 * @param destClass the (primitive) destination class
 * @return The cost of promoting the primitive
 */
private static float getPrimitivePromotionCost(final Class<?> srcClass, final Class<?> destClass) {
    float cost = 0.0f;
    Class<?> cls = srcClass;
    if (!cls.isPrimitive()) {
        // slight unwrapping penalty
        cost += 0.1f;
        cls = ClassUtils.wrapperToPrimitive(cls);
    }
    for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
        if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
            cost += 0.1f;
            if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
                cls = ORDERED_PRIMITIVE_TYPES[i + 1];
            }
        }
    }
    return cost;
}
 
Example 10
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
 * <li>Inner class fields are not appened.</li>
 * </ul>
 *
 * @param field
 *            The Field to test.
 * @return Whether or not to append the given <code>Field</code>.
 */
protected boolean accept(Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // Reject transient fields.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // Reject static fields.
        return false;
    }
    if (this.excludeFieldNames != null
        && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
        // Reject fields from the getExcludeFieldNames list.
        return false;
    }
    return true;
}
 
Example 11
Source Project: webanno   Source File: ProjectSettingsPanelRegistryImpl.java    License: Apache License 2.0 6 votes vote down vote up
void init()
{
    List<ProjectSettingsPanelFactory> exts = new ArrayList<>();

    if (extensionsProxy != null) {
        exts.addAll(extensionsProxy);
        AnnotationAwareOrderComparator.sort(exts);
    
        for (ProjectSettingsPanelFactory fs : exts) {
            log.info("Found project setting panel: {}",
                    ClassUtils.getAbbreviatedName(fs.getClass(), 20));
        }
    }
    
    extensions = Collections.unmodifiableList(exts);
}
 
Example 12
Source Project: vjtools   Source File: ExceptionUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 拼装 短异常类名: 异常信息 <-- RootCause的短异常类名: 异常信息
 */
public static String toStringWithRootCause(@Nullable Throwable t) {
	if (t == null) {
		return StringUtils.EMPTY;
	}

	final String clsName = ClassUtils.getShortClassName(t, null);
	final String message = StringUtils.defaultString(t.getMessage());
	Throwable cause = getRootCause(t);

	StringBuilder sb = new StringBuilder(128).append(clsName).append(": ").append(message);
	if (cause != t) {
		sb.append("; <---").append(toStringWithShortName(cause));
	}

	return sb.toString();
}
 
Example 13
Source Project: vjtools   Source File: AnnotationUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 找出所有标注了该annotation的公共方法(含父类的公共函数),循环其接口.
 * 
 * 暂未支持Spring风格Annotation继承Annotation
 * 
 * 另,如果子类重载父类的公共函数,父类函数上的annotation不会继承,只有接口上的annotation会被继承.
 */
public static <T extends Annotation> Set<Method> getAnnotatedPublicMethods(Class<?> clazz, Class<T> annotation) {
	// 已递归到Objebt.class, 停止递归
	if (Object.class.equals(clazz)) {
		return Collections.emptySet();
	}

	List<Class<?>> ifcs = ClassUtils.getAllInterfaces(clazz);
	Set<Method> annotatedMethods = new HashSet<Method>();

	// 遍历当前类的所有公共方法
	Method[] methods = clazz.getMethods();

	for (Method method : methods) {
		// 如果当前方法有标注,或定义了该方法的所有接口有标注
		if (method.getAnnotation(annotation) != null || searchOnInterfaces(method, annotation, ifcs)) {
			annotatedMethods.add(method);
		}
	}

	return annotatedMethods;
}
 
Example 14
Source Project: sailfish-core   Source File: ComparisonUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static void setTypeAndValue(Map<String, Object> map, Object value) {
    map.put("type", ClassUtils.getSimpleName(value, null));

    if(value instanceof IFilter) {
        IFilter filter = (IFilter)value;

        if(filter.hasValue()) {
            map.put("type", ClassUtils.getSimpleName(value = filter.getValue(), null));
        } else {
            value = filter.getCondition();
        }
    } else if(value instanceof LocalDate || value instanceof LocalTime || value instanceof LocalDateTime) {
        value = JsonMessageConverter.formatTemporal((TemporalAccessor)value);
    }

    map.put("value", value);
}
 
Example 15
Source Project: olingo-odata4   Source File: EntityUUID.java    License: Apache License 2.0 6 votes vote down vote up
public EntityUUID(final URI entitySetURI, final Class<?> type, final Object key) {
  this.entitySetURI = entitySetURI;
  this.key = key;
  this.tempKey = (int) (Math.random() * 1000000);

  if (type == null || !Serializable.class.isAssignableFrom(type)) {
    throw new IllegalArgumentException("Invalid Entity type class: " + type);
  }
  if (this.type == null) {
    for (Class<?> clazz : ClassUtils.hierarchy(type, ClassUtils.Interfaces.INCLUDE)) {
      if (ArrayUtils.contains(clazz.getInterfaces(), EntityType.class)) {
        this.type = clazz;
      }
    }
  }
}
 
Example 16
Source Project: rice   Source File: BusinessObjectBase.java    License: Educational Community License v2.0 6 votes vote down vote up
@Override
public String toString() {
       class BusinessObjectToStringBuilder extends ReflectionToStringBuilder {

           private BusinessObjectToStringBuilder(Object object) {
               super(object);
           }

           @Override
           public boolean accept(Field field) {
               return String.class.isAssignableFrom(field.getType())
                       || ClassUtils.isPrimitiveOrWrapper(field.getType());
           }

       }

       return new BusinessObjectToStringBuilder(this).toString();
   }
 
Example 17
Source Project: poi-tl   Source File: ElementProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(RunTemplate runTemplate) {
    RenderPolicy policy = runTemplate.findPolicy(template.getConfig());
    if (null == policy) {
        throw new RenderException(
                "Cannot find render policy: [" + ((ElementTemplate) runTemplate).getTagName() + "]");
    }
    if (policy instanceof DocxRenderPolicy) {
        return;
    } else {
        LOGGER.info("Start render TemplateName:{}, Sign:{}, policy:{}", runTemplate.getTagName(),
                runTemplate.getSign(), ClassUtils.getShortClassName(policy.getClass()));
        policy.render(((ElementTemplate) runTemplate), renderDataCompute.compute(runTemplate.getTagName()),
                template);
    }

}
 
Example 18
Source Project: ctsms   Source File: IndexResource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private static JsonObject createVONode(Collection<Method> fields, boolean recursive) throws Exception {
	JsonObject voNode = new JsonObject();
	if (fields != null) {
		Iterator<Method> it = fields.iterator();
		while (it.hasNext()) {
			Method field = it.next();
			String fieldName = VO_METHOD_TRANSFILTER.transform(field.getName());
			if (recursive) {
				voNode.add(fieldName, createVOReturnTypeNode(field.getReturnType(), field.getGenericReturnType()));
			} else {
				voNode.addProperty(fieldName, ClassUtils.getSimpleName(field.getReturnType()));
			}
		}
	}
	return voNode;
}
 
Example 19
Source Project: j360-dubbo-app-all   Source File: ClassUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 找出所有标注了该annotation的公共方法(含父类的公共函数),循环其接口.
 * 
 * 暂未支持Spring风格Annotation继承Annotation
 * 
 * 另,如果子类重载父类的公共函数,父类函数上的annotation不会继承,只有接口上的annotation会被继承.
 */
public static <T extends Annotation> Set<Method> getAnnotatedPublicMethods(Class<?> clazz, Class<T> annotation) {
	// 已递归到Objebt.class, 停止递归
	if (Object.class.equals(clazz)) {
		return Collections.emptySet();
	}

	List<Class<?>> ifcs = ClassUtils.getAllInterfaces(clazz);
	Set<Method> annotatedMethods = new HashSet<Method>();

	// 遍历当前类的所有公共方法
	Method[] methods = clazz.getMethods();

	for (Method method : methods) {
		// 如果当前方法有标注,或定义了该方法的所有接口有标注
		if (method.getAnnotation(annotation) != null || searchOnInterfaces(method, annotation, ifcs)) {
			annotatedMethods.add(method);
		}
	}

	return annotatedMethods;
}
 
Example 20
Source Project: o2oa   Source File: ApiBuilder.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Class<?>> scanJaxrsClass() throws Exception {
	try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAnnotationInfo().scan()) {
		SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
		for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
			Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
			for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
					"getClasses")) {
				Path path = o.getAnnotation(Path.class);
				JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
				if (null != path && null != jaxrsDescribe) {
					classes.add(o);
				}
			}
		}
		return classes;
	}
}
 
Example 21
Source Project: o2oa   Source File: Describe.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Class<?>> scanJaxrsClass(String name) throws Exception {
	// String pack = "com." + name.replaceAll("_", ".");
	String pack = "";
	if (StringUtils.startsWith(name, "o2_")) {
		pack = name.replaceAll("_", ".");
	} else {
		pack = "com." + name.replaceAll("_", ".");
	}
	try (ScanResult scanResult = new ClassGraph().whitelistPackages(pack).enableAllInfo().scan()) {
		SetUniqueList<Class<?>> classes = SetUniqueList.setUniqueList(new ArrayList<Class<?>>());
		for (ClassInfo info : scanResult.getClassesWithAnnotation(ApplicationPath.class.getName())) {
			Class<?> applicationPathClass = ClassUtils.getClass(info.getName());
			for (Class<?> o : (Set<Class<?>>) MethodUtils.invokeMethod(applicationPathClass.newInstance(),
					"getClasses")) {
				Path path = o.getAnnotation(Path.class);
				JaxrsDescribe jaxrsDescribe = o.getAnnotation(JaxrsDescribe.class);
				if (null != path && null != jaxrsDescribe) {
					classes.add(o);
				}
			}
		}
		return classes;
	}
}
 
Example 22
public static boolean needConvert(Object obj, JavaType invocationTimeType) {
  if (obj == null || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || invocationTimeType.isPrimitive()
      || ProtoConst.OBJECT_TYPE.equals(invocationTimeType)) {
    return false;
  }

  if (obj.getClass() == invocationTimeType.getRawClass()) {
    return false;
  }

  if (invocationTimeType.getRawClass().isAssignableFrom(obj.getClass())) {
    if (invocationTimeType.getContentType() == null) {
      return false;
    }
  }

  return true;
}
 
Example 23
Source Project: astor   Source File: MemberUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the number of steps required to promote a primitive number to another type.
 * @param srcClass the (primitive) source class
 * @param destClass the (primitive) destination class
 * @return The cost of promoting the primitive
 */
private static float getPrimitivePromotionCost(final Class<?> srcClass,
        final Class<?> destClass) {
    float cost = 0.0f;
    Class<?> cls = srcClass;
    if (!cls.isPrimitive()) {
        // slight unwrapping penalty
        cost += 0.1f;
        cls = ClassUtils.wrapperToPrimitive(cls);
    }
    for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
        if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
            cost += 0.1f;
            if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
                cls = ORDERED_PRIMITIVE_TYPES[i + 1];
            }
        }
    }
    return cost;
}
 
Example 24
private void buildProperties() {
    if (builderClass == null) {
        return;
    }
    try {
        builderClass.getMethod(BUILD_METHOD_NAME);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }

    for (Method method : builderClass.getMethods()) {
        if (method.getParameterCount() == 1 && ClassUtils.isAssignable(builderClass, method.getReturnType())) {
            Class<?> paramType = method.getParameterTypes()[0];
            if (Supplier.class.isAssignableFrom(paramType) || Consumer.class.isAssignableFrom(paramType)) {
                continue;
            }
            if (paramType.isEnum()) {
                properties.put(method.getName(), new TypeTag(paramType, true, method));
            } else if (convertUtilsBean.lookup(paramType) == null) {
                properties.put(method.getName(), new TypeTag(paramType, false, method));
            } else {
                properties.put(method.getName(), new TypeTag(paramType, true, method));
            }
        }
    }
}
 
Example 25
Source Project: incubator-gobblin   Source File: GsonInterfaceAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
  if (ClassUtils.isPrimitiveOrWrapper(type.getRawType()) || type.getType() instanceof GenericArrayType
      || CharSequence.class.isAssignableFrom(type.getRawType())
      || (type.getType() instanceof ParameterizedType && (Collection.class.isAssignableFrom(type.getRawType())
          || Map.class.isAssignableFrom(type.getRawType())))) {
    // delegate primitives, arrays, collections, and maps
    return null;
  }
  if (!this.baseClass.isAssignableFrom(type.getRawType())) {
    // delegate anything not assignable from base class
    return null;
  }
  TypeAdapter<R> adapter = new InterfaceAdapter<>(gson, this, type);
  return adapter;
}
 
Example 26
Source Project: webanno   Source File: AnnotationSidebarRegistryImpl.java    License: Apache License 2.0 6 votes vote down vote up
void init()
{
    List<AnnotationSidebarFactory> exts = new ArrayList<>();

    if (extensionsProxy != null) {
        exts.addAll(extensionsProxy);
        exts.sort(buildComparator());

        for (AnnotationSidebarFactory fs : exts) {
            log.info("Found annotation sidebar extension: {}",
                    ClassUtils.getAbbreviatedName(fs.getClass(), 20));
        }
    }
    
    extensions = Collections.unmodifiableList(exts);
}
 
Example 27
Source Project: ctsms   Source File: IndexResource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private static JsonElement createVOInputTypeNode(Class<?> inputType, Type genericType) throws Exception {
	// no input maps:
	if (isTerminalType(inputType)) {
		return new JsonPrimitive(ClassUtils.getSimpleName(inputType));
	} else {
		boolean isCollection = Collection.class.isAssignableFrom(inputType);
		if (isCollection) {
			try {
				inputType = (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0];
			} catch (Exception e) {
				inputType = Object.class;
			}
		}
		Collection<Method> fields = AssociationPath.listMethods(inputType, VO_METHOD_TRANSFILTER);
		if (isTerminalType(inputType) || fields.size() == 0) {
			return markMapCollection(new JsonPrimitive(ClassUtils.getSimpleName(inputType)), null, false, isCollection);
		} else {
			return markMapCollection(createVONode(fields, true), null, false, isCollection);
		}
	}
}
 
Example 28
/**
 * Parses a string into a type. Returns null if it doesn't succeed.
 * FIXME Only supports parameterized types with at most one type argument.
 * Doesn't support wildcard types.
 *
 * TODO make a real parser someday
 */
private static Type parseType(String t) {
    Matcher matcher = PARAM_TYPE_MATCHER.matcher(t.replaceAll("\\s+", ""));
    if (matcher.matches()) {
        String raw = matcher.group(1);
        Type result;
        try {
            result = ClassUtils.getClass(raw);
        } catch (ClassNotFoundException e) {
            return null;
        }

        String param = matcher.group(3);
        if (StringUtils.isNotBlank(param)) {
            Type paramType = parseType(param);
            if (paramType != null) {
                result = TypeUtils.parameterize((Class) result, paramType);
            }
        }

        String arrayDims = matcher.group(4);
        if (StringUtils.isNotBlank(arrayDims)) {
            int dimensions = StringUtils.countMatches(arrayDims, '[');
            while (dimensions-- > 0) {
                result = TypeUtils.genericArrayType(result);
            }
        }

        return result;
    }
    return null;
}
 
Example 29
Source Project: astor   Source File: MethodUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Find an accessible method that matches the given name and has compatible parameters.
 * Compatible parameters mean that every method parameter is assignable from 
 * the given parameters.
 * In other words, it finds a method with the given name 
 * that will take the parameters given.<p>
 *
 * <p>This method is used by 
 * {@link 
 * #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
 *
 * <p>This method can match primitive parameter by passing in wrapper classes.
 * For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
 * parameter.
 *
 * @param cls find method in this class
 * @param methodName find method with this name
 * @param parameterTypes find method with most compatible parameters 
 * @return The accessible method
 */
public static Method getMatchingAccessibleMethod(Class<?> cls,
        String methodName, Class<?>... parameterTypes) {
    try {
        Method method = cls.getMethod(methodName, parameterTypes);
        MemberUtils.setAccessibleWorkaround(method);
        return method;
    } catch (NoSuchMethodException e) { /* SWALLOW */
    }
    // search through all methods
    Method bestMatch = null;
    Method[] methods = cls.getMethods();
    for (int i = 0, size = methods.length; i < size; i++) {
        if (methods[i].getName().equals(methodName)) {
            // compare parameters
            if (ClassUtils.isAssignable(parameterTypes, methods[i]
                    .getParameterTypes(), true)) {
                // get accessible version of method
                Method accessibleMethod = getAccessibleMethod(methods[i]);
                if (accessibleMethod != null) {
                    if (bestMatch == null
                            || MemberUtils.compareParameterTypes(
                                    accessibleMethod.getParameterTypes(),
                                    bestMatch.getParameterTypes(),
                                    parameterTypes) < 0) {
                        bestMatch = accessibleMethod;
                    }
                }
            }
        }
    }
    if (bestMatch != null) {
        MemberUtils.setAccessibleWorkaround(bestMatch);
    }
    return bestMatch;
}
 
Example 30
private TimelineMetric createTimelineMetric(long currentTimeMillis, String component,
                                            String attributeName, Double attributeValue) {
  TimelineMetric timelineMetric = new TimelineMetric();
  timelineMetric.setMetricName(attributeName);
  timelineMetric.setHostName(hostname);
  if (setInstanceId) {
    timelineMetric.setInstanceId(instanceId);
  }
  timelineMetric.setAppId(component);
  timelineMetric.setStartTime(currentTimeMillis);
  timelineMetric.setType(ClassUtils.getShortCanonicalName(attributeValue, "Number"));
  timelineMetric.getMetricValues().put(currentTimeMillis, attributeValue);
  return timelineMetric;
}