本文整理汇总了Java中org.apache.commons.lang3.reflect.MethodUtils类的典型用法代码示例。如果您正苦于以下问题:Java MethodUtils类的具体用法?Java MethodUtils怎么用?Java MethodUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
MethodUtils类属于org.apache.commons.lang3.reflect包,在下文中一共展示了MethodUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: provideExtractorForValue
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
private <T> ValueExtractor provideExtractorForValue(Class<T> clazz, int target, List<String> chainOfProperties) {
Class<?> propertyClass = clazz;
List<ValueExtractor> chainedExtractors = Lists.newArrayList();
for (String property : chainOfProperties) {
Class<?> finalPropertyClass = propertyClass;
Optional<Method> matchingMethod = Stream.of(property,
"get" + WordUtils.capitalize(property),
"is" + WordUtils.capitalize(property))
.map(token -> MethodUtils.getMatchingMethod(finalPropertyClass, token))
.findFirst();
Method method = matchingMethod.orElseThrow(
() -> new InvalidQueryException(
String.format("Cannot find appropriate method for property [%s] on class [%s]",
property, finalPropertyClass)));
ReflectionExtractor extractor = new ReflectionExtractor(method.getName());
chainedExtractors.add(extractor);
propertyClass = method.getDeclaringClass();
}
return new ChainedExtractor(chainedExtractors.toArray(new ValueExtractor[chainedExtractors.size()]));
}
示例2: invokePublic
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
*
* 快捷调用公共方法(性能较差)
*
* @param host
* 宿主对象
* @param name
* 方法名
* @param args
* 方法参数
* @return 执行结果
* @throws NoSuchMethodException
* 如果没有相应的方法
*/
public static Object invokePublic(Object host, String name, Object... args) throws NoSuchMethodException {
final Class<?> clazz = host instanceof Class ? (Class<?>) host : host.getClass();
args = args == null ? new Object[] { null } : args;
Class<?>[] paramTypes = new Class[args.length];
for (int i = 0; i < paramTypes.length; i++) {
paramTypes[i] = args[i] == null ? null : args[i].getClass();
}
int[] keys = new int[3];
keys[0] = clazz.hashCode();
keys[1] = name.hashCode();
keys[2] = Arrays.hashCode(paramTypes);
int key = Arrays.hashCode(keys);
Invoker invoker = PUBLIC_INVOKER_MAP.get(key);
if (invoker == null) {
Method method = MethodUtils.getMatchingAccessibleMethod(clazz, name, paramTypes);
if (method == null) {
throw new NoSuchMethodException(clazz.getName() + "." + name + argumentTypesToString(paramTypes));
}
invoker = newInvoker(method);
PUBLIC_INVOKER_MAP.put(key, invoker);
}
return invoker.invoke(host, args);
}
示例3: checkCommands
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
private void checkCommands(final String os, final String... command) throws ReflectiveOperationException {
final URL[] urLs = ((URLClassLoader) Main.class.getClassLoader()).getURLs();
ThreadClassLoaderScope scope = null;
try {
System.setProperty("os.name", os);
final URLClassLoader urlClassLoader = new URLClassLoader(urLs, null);
scope = new ThreadClassLoaderScope(urlClassLoader);
final Object terra = urlClassLoader.loadClass("org.ligoj.app.plugin.prov.terraform.TerraformUtils").newInstance();
final Object mock = MethodUtils.invokeStaticMethod(urlClassLoader.loadClass("org.mockito.Mockito"), "mock",
urlClassLoader.loadClass("org.ligoj.bootstrap.resource.system.configuration.ConfigurationResource"));
FieldUtils.writeField(terra, "configuration", mock, true);
Assert.assertEquals(Arrays.asList(command),
((ProcessBuilder) MethodUtils.invokeMethod(terra, true, "newBuilder", new Object[] { new String[] { "terraform" } }))
.command());
} finally {
IOUtils.closeQuietly(scope);
}
}
示例4: matchingModuleMethod
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* 匹配模块中复合HTTP请求路径的方法
* 匹配方法的方式是:HttpMethod和HttpPath全匹配
*
* @param path HTTP请求路径
* @param httpMethod HTTP请求方法
* @param uniqueId 模块ID
* @param classOfModule 模块类
* @return 返回匹配上的方法,如果没有找到匹配方法则返回null
*/
private Method matchingModuleMethod(final String path,
final Http.Method httpMethod,
final String uniqueId,
final Class<?> classOfModule) {
for (final Method method : MethodUtils.getMethodsListWithAnnotation(classOfModule, Http.class)) {
final Http httpAnnotation = method.getAnnotation(Http.class);
if(null == httpAnnotation) {
continue;
}
final String pathPattern = "/"+uniqueId+httpAnnotation.value();
if (ArrayUtils.contains(httpAnnotation.method(), httpMethod)
&& SandboxStringUtils.matching(path, pathPattern)) {
return method;
}
}
// 找不到匹配方法,返回null
return null;
}
示例5: formatObjectGraph
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
@Override
public String formatObjectGraph(Object graph) throws ReflectiveOperationException, ClassCastException {
StringBuilder out = new StringBuilder();
Enumeration attrs = (Enumeration) MethodUtils.invokeExactMethod(graph, "getAttributeNames");
@SuppressWarnings("unchecked")
ArrayList<String> attrList = Collections.list(attrs);
Collections.sort(attrList);
out.append("{");
int size = attrList.size();
for (int i = 0; i < size; i++) {
String attrName = attrList.get(i);
Object attrValue = MethodUtils.invokeExactMethod(graph, "getAttribute", attrName);
out.append(attrName);
out.append('=');
out.append(attrValue);
if (i != size - 1) {
out.append(",\n\n");
}
}
out.append("}");
return out.toString();
}
示例6: applyRemoversToOriginal
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
private T applyRemoversToOriginal(T original, Mutant<T> mutant) {
try {
T modifiedOriginal = (T) MethodUtils.invokeMethod(original, "duplicate");
List<Mutant<T>> list = Arrays.asList(new Mutant<>(modifiedOriginal, ""));
for (MutantRemover mutantRemover : mutant.getRemoversApplied()) {
list = mutantRemover.removeMutants(list);
}
if (list.size() != 1) {
throw new RuntimeException("Applying the MutantRemovers used for a "
+ "mutant on the original schema did not produce only 1 "
+ "schema (expected: 1, actual: " + list.size() + ")");
}
return list.get(0).getMutatedArtefact();
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
throw new RuntimeException("Unable to execute the 'duplicate' "
+ "method in a class that appears to have an accessible "
+ "duplicate method to call", ex);
}
}
示例7: injectValueInFirstArg
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
private void injectValueInFirstArg(List<SlimAssertion> assertions, boolean not, Object contentToCheck) {
SlimAssertion.getInstructions(assertions).forEach(instruction -> {
try {
String valueToInject = FitnesseMarkup.SELECTOR_VALUE_SEPARATOR + (not ? FitnesseMarkup.SELECTOR_VALUE_DENY_INDICATOR : StringUtils.EMPTY) + contentToCheck;
Object args = FieldUtils.readField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_ARGS_FIELD, true);
Object[] argsToInject;
if (args instanceof Object[] && ArrayUtils.getLength(args) > NumberUtils.INTEGER_ZERO) {
argsToInject = (Object[]) args;
argsToInject[NumberUtils.INTEGER_ZERO] += valueToInject;
} else {
argsToInject = ArrayUtils.toArray(valueToInject);
}
String methodName = Objects.toString(FieldUtils.readField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_METHODNAME_FIELD, true));
if (Objects.isNull(MethodUtils.getAccessibleMethod(SeleniumFixture.class, Objects.toString(methodName), ClassUtils.toClass(argsToInject)))) {
SeleniumScriptTable.LOGGER.fine("Method for instruction not found on SeleniumFixture, injection aborted: " + instruction);
return;
}
FieldUtils.writeField(instruction, SeleniumScriptTable.CALL_INSTRUCTION_ARGS_FIELD, argsToInject, true);
} catch (IllegalArgumentException | ReflectiveOperationException e) {
SeleniumScriptTable.LOGGER.log(Level.FINE, "Failed to inject check value using reflection", e);
}
});
}
示例8: findAnnotation
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* 获得运行的annotaion.
*
* <h3>代码流程:</h3>
*
* <blockquote>
* <ol>
* <li>先基于 {@link org.aspectj.lang.reflect.MethodSignature},获得其 method,然后继续这个method 调用
* {@link org.springframework.core.annotation.AnnotationUtils#findAnnotation(Method, Class)}解析</li>
* <li>如果第一步找不到相应的annotation,那么会通过 {@link org.aspectj.lang.JoinPoint#getTarget()} 构建target method,并解析</li>
* </ol>
* </blockquote>
*
* @param <T>
* the generic type
* @param joinPoint
* the join point
* @param annotationClass
* the annotation class
* @return the annotation
*/
public static <T extends Annotation> T findAnnotation(JoinPoint joinPoint,Class<T> annotationClass){
Validate.notNull(joinPoint, "joinPoint can't be null!");
Validate.notNull(annotationClass, "annotationClass can't be null!");
//---------------------------------------------------------------
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
T annotation = AnnotationUtils.findAnnotation(method, annotationClass);
if (null != annotation){
return annotation;
}
//---------------------------------------------------------------
Method targetMethod = MethodUtils
.getAccessibleMethod(joinPoint.getTarget().getClass(), method.getName(), method.getParameterTypes());
annotation = AnnotationUtils.findAnnotation(targetMethod, annotationClass);
if (null != annotation){
return annotation;
}
return null;
}
示例9: getLogger
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* Gets the logger.
*
* @param name the name
* @return the logger
*/
public Jdk14LoggerAccessor getLogger(String name) {
try {
Object logger = MethodUtils.invokeMethod(getTarget(), "getLogger", name);
if (logger == null) {
throw new NullPointerException(
getTarget().getClass().getName() + "#getLogger(\"" + name + "\") returned null");
}
Jdk14LoggerAccessor accessor = new Jdk14LoggerAccessor();
accessor.setTarget(logger);
accessor.setApplication(getApplication());
return accessor;
} catch (Exception e) {
logger.error("{}#getLogger('{}') failed", getTarget().getClass().getName(), name, e);
}
return null;
}
示例10: getHandlers
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* Gets the handlers.
*
* @return the handlers
*/
@SuppressWarnings("unchecked")
public List<LogDestination> getHandlers() {
List<LogDestination> allHandlers = new ArrayList<>();
try {
for (String name : Collections
.list((Enumeration<String>) MethodUtils.invokeMethod(getTarget(), "getLoggerNames"))) {
Jdk14LoggerAccessor accessor = getLogger(name);
if (accessor != null) {
allHandlers.addAll(accessor.getHandlers());
}
}
} catch (Exception e) {
logger.error("{}#getLoggerNames() failed", getTarget().getClass().getName(), e);
}
return allHandlers;
}
示例11: getHandlers
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* Gets the handlers.
*
* @return the handlers
*/
public List<LogDestination> getHandlers() {
List<LogDestination> handlerAccessors = new ArrayList<>();
try {
Object[] handlers = (Object[]) MethodUtils.invokeMethod(getTarget(), "getHandlers");
for (int h = 0; h < handlers.length; h++) {
Object handler = handlers[h];
Jdk14HandlerAccessor handlerAccessor = wrapHandler(handler, h);
if (handlerAccessor != null) {
handlerAccessors.add(handlerAccessor);
}
}
} catch (Exception e) {
logger.error("{}#handlers inaccessible", getTarget().getClass().getName(), e);
}
return handlerAccessors;
}
示例12: getLevel
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* Gets the level.
*
* @return the level
*/
public String getLevel() {
try {
Object level = null;
Object target = getTarget();
while (level == null && target != null) {
level = getLevelInternal(target);
target = MethodUtils.invokeMethod(target, "getParent");
}
if (level == null && isJuliRoot()) {
return "INFO";
}
return (String) MethodUtils.invokeMethod(level, "getName");
} catch (Exception e) {
logger.error("{}#getLevel() failed", getTarget().getClass().getName(), e);
}
return null;
}
示例13: getAppender
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* Returns the appender of this logger with the given name.
*
* @param name the name of the appender to return
* @return the appender with the given name, or null if no such appender exists for this logger
*/
public LogbackAppenderAccessor getAppender(String name) {
try {
Object appender = MethodUtils.invokeMethod(getTarget(), "getAppender", name);
if (appender == null) {
List<LogbackAppenderAccessor> appenders = getAppenders();
for (LogbackAppenderAccessor wrappedAppender : appenders) {
if (wrappedAppender.getIndex().equals(name)) {
return wrappedAppender;
}
}
}
return wrapAppender(appender);
} catch (Exception e) {
logger.error("{}#getAppender() failed", getTarget().getClass().getName(), e);
}
return null;
}
示例14: getSiftedAppenders
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* Gets the sifted appenders.
*
* @param appender the appender
* @return the sifted appenders
* @throws Exception the exception
*/
@SuppressWarnings("unchecked")
private List<Object> getSiftedAppenders(Object appender) throws Exception {
if ("ch.qos.logback.classic.sift.SiftingAppender".equals(appender.getClass().getName())) {
Object tracker = MethodUtils.invokeMethod(appender, "getAppenderTracker");
if (tracker != null) {
try {
return (List<Object>) MethodUtils.invokeMethod(tracker, "allComponents");
} catch (final NoSuchMethodException e) {
// XXX Legacy 1.0.x and lower support for logback
logger.trace("", e);
return (List<Object>) MethodUtils.invokeMethod(tracker, "valueList");
}
}
return new ArrayList<>();
}
return null;
}
示例15: LogbackFactoryAccessor
import org.apache.commons.lang3.reflect.MethodUtils; //导入依赖的package包/类
/**
* Attempts to initialize a Logback logger factory via the given class loader.
*
* @param cl the ClassLoader to use when fetching the factory
* @throws ClassNotFoundException the class not found exception
* @throws IllegalAccessException the illegal access exception
* @throws InvocationTargetException the invocation target exception
*/
public LogbackFactoryAccessor(ClassLoader cl)
throws ClassNotFoundException, IllegalAccessException, InvocationTargetException {
// Get the singleton SLF4J binding, which may or may not be Logback, depending on the binding.
Class<?> clazz = cl.loadClass("org.slf4j.impl.StaticLoggerBinder");
Method getSingleton = MethodUtils.getAccessibleMethod(clazz, "getSingleton", new Class[0]);
Object singleton = getSingleton.invoke(null);
Method getLoggerFactory =
MethodUtils.getAccessibleMethod(clazz, "getLoggerFactory", new Class[0]);
Object loggerFactory = getLoggerFactory.invoke(singleton);
// Check if the binding is indeed Logback
Class<?> loggerFactoryClass = cl.loadClass("ch.qos.logback.classic.LoggerContext");
if (!loggerFactoryClass.isInstance(loggerFactory)) {
throw new RuntimeException("The singleton SLF4J binding was not Logback");
}
setTarget(loggerFactory);
}