com.github.siwenyan.reflection.MethodContainer Maven / Gradle / Ivy
package com.github.siwenyan.reflection;
import java.lang.reflect.Method;
public class MethodContainer {
private Object invokeFrom;
private Method method;
public MethodContainer(Object invokeFrom, Method method) {
this.invokeFrom = invokeFrom;
this.method = method;
}
public MethodContainer(Object invokeFrom, String methodName, Class>... paramTypes) {
try {
Method targetMethod = null;
Class extends Object> clazz = invokeFrom.getClass();
targetMethod = clazz.getDeclaredMethod(methodName, paramTypes);
this.method = targetMethod;
this.invokeFrom = invokeFrom;
} catch (Exception e) {
throw new RuntimeException("Invalid method: " + methodName);
}
}
public MethodContainer(Object invokeFrom, String methodName) {
Method targetMethod = null;
Class extends Object> clazz = invokeFrom.getClass();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
if (null == targetMethod) {
targetMethod = method;
} else {
throw new RuntimeException("More than one method found: " + methodName);
}
}
}
if (null == targetMethod) {
throw new RuntimeException("No method found: " + methodName);
}
this.method = targetMethod;
this.invokeFrom = invokeFrom;
}
public MethodContainer(Class> invokeType, String methodName, Class>... paramTypes) {
try {
Method targetMethod = null;
targetMethod = invokeType.getDeclaredMethod(methodName, paramTypes);
if (!ReflectionUtils.isStaticMethod(targetMethod)) {
throw new RuntimeException("Non-static method: " + methodName);
}
this.method = targetMethod;
this.invokeFrom = null;
} catch (Exception e) {
throw new RuntimeException("Invalid method: " + method);
}
}
public MethodContainer(Class> invokeType, String methodName) {
Method targetMethod = null;
Method[] methods = invokeType.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
if (ReflectionUtils.isStaticMethod(method)) {
if (null != targetMethod) {
throw new RuntimeException("More than one method found: " + methodName);
} else {
targetMethod = method;
}
}
}
}
if (null == targetMethod) {
throw new RuntimeException("No method found: " + methodName);
}
this.method = targetMethod;
this.invokeFrom = null;
}
public Method getMethod() {
return this.method;
}
public Object getInvokeFrom() {
return this.invokeFrom;
}
}