要获取方法的参数值,你首先需要有一个类的实例,并且需要能够实际调用该方法。在Java中,方法的参数值是在方法被调用时由调用者传入的,因此,你不能直接从外部“获取”一个未调用方法的参数值。
下面是一个简单的示例,演示了如何创建一个类的实例,调用一个被注解标记的方法,并在调用过程中捕获参数值:
java复制代码
| import java.lang.reflect.Method;  | |
| public class AnnotationParser {  | |
| public static void main(String[] args) throws Exception {  | |
| MyClass myClassInstance = new MyClass();  | |
| Class<MyClass> clazz = MyClass.class;  | |
| Method[] methods = clazz.getDeclaredMethods();  | |
| for (Method method : methods) {  | |
| if (method.isAnnotationPresent(MyCustomAnnotation.class)) {  | |
| // 假设我们知道方法的参数类型和需要传递的值  | |
| // 在这个例子中,我们硬编码了参数值作为演示  | |
| Object[] argsForCall;  | |
| Class<?>[] parameterTypes = method.getParameterTypes();  | |
| if (parameterTypes.length == 0) {  | |
| argsForCall = null; // 无参数方法  | |
| } else if (parameterTypes.length == 1 && parameterTypes[0] == String.class) {  | |
| argsForCall = new Object[]{"Hello, World!"}; // 一个String参数  | |
| } else if (parameterTypes.length == 2 && parameterTypes[0] == String.class && parameterTypes[1] == int.class) {  | |
| argsForCall = new Object[]{"Example", 42}; // 一个String参数和一个int参数  | |
| } else {  | |
| continue; // 如果参数不匹配,则跳过此方法  | |
| }  | |
| // 调用方法并捕获返回值(如果有的话)  | |
| Object result = method.invoke(myClassInstance, argsForCall);  | |
| // 打印方法名、参数值和返回值  | |
| System.out.println("Method Name: " + method.getName());  | |
| System.out.println("Parameters: " + Arrays.toString(argsForCall));  | |
| System.out.println("Return Value: " + result);  | |
| }  | |
| }  | |
| }  | |
| }  | |
| class MyClass {  | |
| @MyCustomAnnotation  | |
| public void myMethod1(String arg1, int arg2) {  | |
| System.out.println("Inside myMethod1: " + arg1 + ", " + arg2);  | |
| // 方法体  | |
| }  | |
| // ... 其他方法 ...  | |
| } | 
在这个示例中,我们创建了一个MyClass的实例,并遍历了它的所有方法。对于每个被@MyCustomAnnotation注解的方法,我们根据方法的参数类型构建了参数数组argsForCall,然后使用Method.invoke()来调用该方法。在调用过程中,我们传入了类的实例和参数数组。
请注意,这个示例假设我们知道如何根据方法的参数类型构建参数数组。在实际应用中,你可能需要根据实际情况动态确定参数值。此外,错误处理和异常捕获在这个示例中被省略了,但在实际应用中是必不可少的。
还要注意的是,反射调用方法的性能通常比直接调用方法要差,因此应谨慎使用,并尽量避免在性能敏感的代码路径中使用反射。