要安全地获取 java.lang.reflect.Method 对象,可以使用以下代码示例:
import java.lang.reflect.Method;
public class SafeGetMethodExample {
public static void main(String[] args) {
try {
// 获取目标类的 Class 对象
Class> targetClass = TargetClass.class;
// 获取方法名和参数类型
String methodName = "targetMethod";
Class>[] parameterTypes = {String.class, int.class};
// 获取 Method 对象
Method method = targetClass.getMethod(methodName, parameterTypes);
// 输出方法信息
System.out.println("方法名:" + method.getName());
System.out.println("返回类型:" + method.getReturnType());
System.out.println("参数类型:");
for (Class> parameterType : method.getParameterTypes()) {
System.out.println(parameterType);
}
} catch (NoSuchMethodException e) {
System.out.println("找不到指定的方法");
}
}
}
class TargetClass {
public void targetMethod(String param1, int param2) {
// 方法实现
}
}
在上面的示例中,我们首先获取了目标类 TargetClass 的 Class 对象。然后,通过指定方法名和参数类型,使用 getMethod()
方法来获取 Method 对象。最后,我们使用 Method 对象来输出方法的信息,包括方法名、返回类型和参数类型。
请注意,由于 getMethod()
方法会抛出 NoSuchMethodException
异常,因此我们需要在代码中进行异常处理。
上一篇:安全地缓存和存储个人访问令牌
下一篇:安全地获取嵌套的JSON对象