下面列出了org.apache.commons.lang3.reflect.MethodUtils#getAccessibleMethod ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected Method findLinkInvokeMethod(Class cls, String methodName) {
Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, Entity.class, String.class);
if (exactMethod != null) {
return exactMethod;
}
// search through all methods
Method[] methods = cls.getMethods();
for (Method availableMethod : methods) {
if (availableMethod.getName().equals(methodName)) {
if (availableMethod.getParameterCount() == 2
&& Void.TYPE.equals(availableMethod.getReturnType())) {
if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0]) &&
String.class == availableMethod.getParameterTypes()[1]) {
// get accessible version of method
return MethodUtils.getAccessibleMethod(availableMethod);
}
}
}
}
return null;
}
@Nullable
protected Method findGeneratorMethod(Class cls, String methodName) {
Method exactMethod = MethodUtils.getAccessibleMethod(cls, methodName, Entity.class);
if (exactMethod != null) {
return exactMethod;
}
// search through all methods
Method[] methods = cls.getMethods();
for (Method availableMethod : methods) {
if (availableMethod.getName().equals(methodName)) {
if (availableMethod.getParameterCount() == 1
&& Component.class.isAssignableFrom(availableMethod.getReturnType())) {
if (Entity.class.isAssignableFrom(availableMethod.getParameterTypes()[0])) {
// get accessible version of method
return MethodUtils.getAccessibleMethod(availableMethod);
}
}
}
}
return null;
}
protected Object convertFromStringUnresolved(Class<?> parameterClass, String paramValueStr) {
try {
Constructor constructor = ConstructorUtils.getAccessibleConstructor(parameterClass, String.class);
if (constructor != null) {
return constructor.newInstance(paramValueStr);
} else {
Method valueOf = MethodUtils.getAccessibleMethod(parameterClass, "valueOf", String.class);
if (valueOf != null) {
return valueOf.invoke(null, paramValueStr);
}
}
} catch (ReflectiveOperationException e) {
throw new ReportingException(
String.format("Could not instantiate object with class [%s] from [%s] string.",
parameterClass.getCanonicalName(),
paramValueStr));
}
return paramValueStr;
}
private static void addDreamcraftItemListItems(Collection LuVMachines){
try {
Class customItemListClass = Class.forName("com.dreammaster.gthandler.CustomItemList");
Method hasnotBeenSet = MethodUtils.getAccessibleMethod(customItemListClass, "hasBeenSet");
Method get = MethodUtils.getAccessibleMethod(customItemListClass, "get", long.class, Object[].class);
for (Enum customItemList : (Enum[]) FieldUtils.getField(customItemListClass, "$VALUES", true).get(null)) {
if (customItemList.toString().contains("LuV") && (boolean) hasnotBeenSet.invoke(customItemList))
LuVMachines.add((ItemStack) get.invoke(customItemList, 1, new Object[0]));
}
} catch (IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
e.printStackTrace();
}
}
@Before
public void setUp() throws Exception {
new Expectations() {
{
operation.getProducerInstance();
result = new Controller();
operation.getProducerMethod();
result = MethodUtils.getAccessibleMethod(Controller.class, "op", String.class, Model.class);
invocation.toProducerArguments();
result = new Object[] {null, new Model()};
}
};
}
public static Classifier cloneClassifier(final Classifier c) throws Exception {
Method cloneMethod = MethodUtils.getAccessibleMethod(c.getClass(), "clone");
if (cloneMethod != null) {
return (Classifier) cloneMethod.invoke(c);
}
return AbstractClassifier.makeCopy(c);
}
static <T> String getInvokeValue(T t, String methodName) {
try {
Method method = MethodUtils.getAccessibleMethod(t.getClass(),
methodName);
String text = TransformUtils.toString(method.invoke(t));
return text;
} catch (Exception e) {
return null;
}
}
@Override
public void run() {
userActionsLog.trace("Menu item {} triggered", item.getId());
StopWatch sw = createStopWatch(item);
Object beanInstance = beanLocator.get(bean);
try {
Method methodWithParams = MethodUtils.getAccessibleMethod(beanInstance.getClass(), beanMethod, Map.class);
if (methodWithParams != null) {
methodWithParams.invoke(beanInstance, params);
return;
}
Method methodWithScreen = MethodUtils.getAccessibleMethod(beanInstance.getClass(), beanMethod, FrameOwner.class);
if (methodWithScreen != null) {
methodWithScreen.invoke(beanInstance, origin);
return;
}
MethodUtils.invokeMethod(beanInstance, beanMethod, (Object[]) null);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Unable to execute bean method", e);
}
sw.stop();
}
protected Object getComposition(FieldGroup.FieldConfig fc) {
Method getCompositionMethod = MethodUtils.getAccessibleMethod(fc.getClass(), "getComponent");
Object composition;
try {
composition = getCompositionMethod.invoke(fc);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Invoke error", e);
}
return ((Component) composition).unwrap(Object.class);
}
@Test
public void testCustomGetCommonSuperClassImplementation() throws Exception {
// augment method to take in a single int argument
methodNode.desc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
// augment method instructions
VariableTable varTable = new VariableTable(classNode, methodNode);
Class<?> iterableClass = Iterable.class;
Constructor arrayListConstructor = ConstructorUtils.getAccessibleConstructor(ArrayList.class);
Constructor linkedListConstructor = ConstructorUtils.getAccessibleConstructor(LinkedList.class);
Constructor hashSetConstructor = ConstructorUtils.getAccessibleConstructor(HashSet.class);
Method iteratorMethod = MethodUtils.getAccessibleMethod(iterableClass, "iterator");
Type iterableType = Type.getType(iterableClass);
Variable testArg = varTable.getArgument(1);
Variable listVar = varTable.acquireExtra(iterableType);
/**
* Collection it;
* switch(arg1) {
* case 0:
* it = new ArrayList()
* break;
* case 1:
* it = new LinkedList()
* break;
* case 2:
* it = new HashSet()
* break;
* default: throw new RuntimeException("must be 0 or 1");
* }
* list.iterator();
*/
LabelNode invokePoint = new LabelNode();
InsnList methodInsnList
= merge(tableSwitch(loadVar(testArg),
throwRuntimeException("must be 0 or 1"),
0,
merge(
construct(arrayListConstructor),
saveVar(listVar),
jumpTo(invokePoint)
),
merge(
construct(linkedListConstructor),
saveVar(listVar),
jumpTo(invokePoint)
),
merge(
construct(hashSetConstructor),
saveVar(listVar),
jumpTo(invokePoint)
)
),
addLabel(invokePoint),
call(iteratorMethod, GenericGenerators.loadVar(listVar)),
pop(), // discard results of call
returnVoid()
);
methodNode.instructions = methodInsnList;
// attemp to write out class -- since we're branching like this it should call getCommonSuperClass() with the types specified in
// each of the switch cases. getCommonsuperClass() is the logic we explictly override and are testing. createJarAndLoad uses
// simpleclasswriter
try (URLClassLoader cl = createJarAndLoad(classNode)) {
Object obj = cl.loadClass("SimpleStub").newInstance();
// there should not be any verifer errors here
MethodUtils.invokeMethod(obj, "fillMeIn", 0);
MethodUtils.invokeMethod(obj, "fillMeIn", 1);
MethodUtils.invokeMethod(obj, "fillMeIn", 2);
}
}
@Test
public void testVertificationWithoutUsingClassLoader() throws Exception {
// augment method to take in a single int argument
methodNode.desc = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
// augment method instructions
VariableTable varTable = new VariableTable(classNode, methodNode);
Class<?> iterableClass = Iterable.class;
Constructor arrayListConstructor = ConstructorUtils.getAccessibleConstructor(ArrayList.class);
Constructor linkedListConstructor = ConstructorUtils.getAccessibleConstructor(LinkedList.class);
Constructor hashSetConstructor = ConstructorUtils.getAccessibleConstructor(HashSet.class);
Method iteratorMethod = MethodUtils.getAccessibleMethod(iterableClass, "iterator");
Type iterableType = Type.getType(iterableClass);
VariableTable.Variable testArg = varTable.getArgument(1);
VariableTable.Variable listVar = varTable.acquireExtra(iterableType);
/**
* Collection it;
* switch(arg1) {
* case 0:
* it = new ArrayList()
* break;
* case 1:
* it = new LinkedList()
* break;
* case 2:
* it = new HashSet()
* break;
* default: throw new RuntimeException("must be 0 or 1");
* }
* list.iterator();
*/
LabelNode invokePoint = new LabelNode();
InsnList methodInsnList
= merge(tableSwitch(loadVar(testArg),
throwRuntimeException("must be 0 or 1"),
0,
merge(
construct(arrayListConstructor),
saveVar(listVar),
jumpTo(invokePoint)
),
merge(
construct(linkedListConstructor),
saveVar(listVar),
jumpTo(invokePoint)
),
merge(
construct(hashSetConstructor),
saveVar(listVar),
jumpTo(invokePoint)
)
),
addLabel(invokePoint),
call(iteratorMethod, loadVar(listVar)),
pop(), // discard results of call
returnVoid()
);
methodNode.instructions = methodInsnList;
// write out class and read it back in again so maxes and frames can be properly computed for frame analyzer
SimpleClassWriter writer = new SimpleClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS, classRepo);
classNode.accept(writer);
byte[] data = writer.toByteArray();
ClassReader cr = new ClassReader(data);
classNode = new SimpleClassNode();
cr.accept(classNode, 0);
methodNode = classNode.methods.get(1);
// analyze
Frame<BasicValue>[] frames;
try {
frames = new Analyzer<>(new SimpleVerifier(classRepo)).analyze(classNode.name, methodNode);
} catch (AnalyzerException ae) {
throw new IllegalArgumentException("Analyzer failed to analyze method", ae);
}
// get last frame
Frame frame = frames[frames.length - 1];
BasicValue basicValue = (BasicValue) frame.getLocal(listVar.getIndex());
// ensure that that the local variable for the collection we created in the switch blocks is an abstract type
assertEquals("java/util/AbstractCollection", basicValue.getType().getInternalName());
}
private boolean hasMatchingParametersMethod(final Method method)
{
return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}
/**
* Checks whether a method for the passed in parameters can be found.
*
* @param method the listener method invoked
* @return a flag whether the parameters could be matched
*/
private boolean hasMatchingParametersMethod(final Method method) {
return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}
/**
* Checks whether a method for the passed in parameters can be found.
*
* @param method the listener method invoked
* @return a flag whether the parameters could be matched
*/
private boolean hasMatchingParametersMethod(final Method method) {
return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}
/**
* Checks whether a method for the passed in parameters can be found.
*
* @param method the listener method invoked
* @return a flag whether the parameters could be matched
*/
private boolean hasMatchingParametersMethod(final Method method) {
return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
}