反射类 Method类的使用

本文详细介绍了Java反射中Method类的使用方法,包括如何获取方法名、参数类型、注解等信息,并通过示例展示了如何读取方法级别的注解及参数级别的注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

反射类 Method类的使用

   在Java反射中,可以使用Method类获取类,参数类型,方法注解,参数注解,方法返回值等信息,在使用Method类中,常会用到以下的方法。如下表所示。

 
方法名 作用

getName()

 获取方法名
isVarArgs() 如果该方法声明为采用可变数量的参数,则返回true; 否则返回false
getModifiers() 获取权限修饰符
getReturnType() 获取返回类型
getExceptionTypes() 获取所有抛出的异常类型
getGenericReturnType 返回Type类型
getParameterTypes() 获取所有参数的类型
getParameterCount() 获取所有参数的个数
getAnnotations()获取方法级别的注解
getDeclaringClass 获取方法所在的类信息

  

  使用如下的示例说明Method类的使用,下面代码段定义了两个参数级别的注解,在MethodService类中给定了一个login()方法,三个入参,其中两个参数使用注解进行标注。观察main()方法的结果。

 1 package com.zzz.mybatis.reflect;
 2 
 3 import java.lang.annotation.Documented;
 4 import java.lang.annotation.ElementType;
 5 import java.lang.annotation.Retention;
 6 import java.lang.annotation.RetentionPolicy;
 7 import java.lang.annotation.Target;
 8 
 9 @Documented
10 @Retention(RetentionPolicy.RUNTIME)
11 @Target(ElementType.PARAMETER)
12 public @interface Name {
13     //默认为空
14     String name() default  "lisi";
15 }

 

 1 package com.zzz.mybatis.reflect;
 2 
 3 import java.lang.annotation.ElementType;
 4 import java.lang.annotation.Retention;
 5 import java.lang.annotation.RetentionPolicy;
 6 import java.lang.annotation.Target;
 7 @Retention(RetentionPolicy.RUNTIME)
 8 @Target(ElementType.PARAMETER)
 9 public @interface Password {
10     //默认为空
11     String password() default  "";
12 }
 1 package com.zzz.mybatis.reflect;
 2 
 3 import java.lang.annotation.Annotation;
 4 import java.lang.reflect.AnnotatedType;
 5 import java.lang.reflect.Method;
 6 import java.lang.reflect.Parameter;
 7 
 8 public class MethodService {
 9     @Deprecated
10     public void login(@Name(name="zhangsan") String name,@Password(password="123") String pwd,int age) throws NullPointerException,IllegalArgumentException {
11 
12     }
13 
14     public static void getAnnotations(Method method) {
15         String name="",pwd="";
16         Annotation[][] ans=method.getParameterAnnotations();
17         int anslen=ans.length;
18          for (int paramIndex = 0; paramIndex < anslen; paramIndex++) {
19               for (Annotation annotation : ans[paramIndex]) {
20                   //判断是否是Param标签的子类,也就是说@param中是否存在value值
21                 if (annotation instanceof Name) {
22                   name = ((Name) annotation).name();
23                   break;
24                 }
25                 if (annotation instanceof Password) {
26                     pwd=((Password)annotation).password();
27                     break;
28                 }
29               }
30          }
31          System.out.println("name"+name+"\t"+"pwd"+pwd);
32     }
33 
34     public static void getActualParameter(Method method) {
35         System.out.println("获取参数个数"+method.getParameterCount());
36         Class<?>[] parameterTypes= method.getParameterTypes();
37         System.out.println("获取所有参数类型");
38         for(Class<?> type:parameterTypes) {
39             System.out.println(type.getName());
40         }
41         System.out.println("获取所有注解");
42         AnnotatedType[] ans=method.getAnnotatedParameterTypes();
43         for(AnnotatedType annotation:ans) {
44             System.out.println(annotation.getClass().getName());
45         }
46         System.out.println("获取完整参数信息");
47       Parameter[] parameters=method.getParameters();
48       for(Parameter parameter:parameters) {
49           System.out.println("参数修饰符:"+parameter.getModifiers()+"参数名:"+parameter.getName()+"参数类型:"+parameter.getType().getName());
50       }
51     }
52 
53 
54     public static void getException(Method method) {
55          Class<?>[] exs=method.getExceptionTypes();
56          for(Class<?> e:exs) {
57              System.out.println(e.getName());
58          }
59     }
60 
61     public static void getMethodAnotation(Method method) {
62         Annotation[] annotations=method.getAnnotations();
63         for(Annotation annotation:annotations) {
64             System.out.println(annotation.annotationType().getName());
65         }
66 
67     }
68 
69     public static void main(String[] args) throws ClassNotFoundException {
70         Class<?> c=Class.forName("com.zzz.mybatis.reflect.MethodService");
71         Method[] methods= c.getMethods();
72         for(Method method:methods) {
73             Class<?>[] paramTypes=method.getParameterTypes();
74             //获取方法名
75             if(method.getName().contains("login")) {
76                 //获取方法所在的类 com.zzz.mybatis.reflect.MethodService
77                 System.out.println("方法所在的类信息:"+method.getDeclaringClass().getName());
78                 //获取方法返回的类型
79                 System.out.println("返回类型:"+method.getReturnType().getName());
80                 //跟getReturnType()类型,不过返回的是一个Type类型
81                 System.out.println("返回Type类型:"+method.getGenericReturnType().getTypeName());
82                 //参数相关
83                 getActualParameter(method);
84                 //获取参数级别的注解信息
85                 getAnnotations(method);
86                 //获取抛出的异常信息
87                 getException(method);
88                 //获取方法级别的注解信息
89                 getMethodAnotation(method);
90         }
91     }
92 
93 }
94 }

 

 1 方法所在的类信息:com.zzz.mybatis.reflect.MethodService
 2 返回类型:void
 3 返回Type类型:void
 4 获取参数个数3
 5 获取所有参数类型
 6 java.lang.String
 7 java.lang.String
 8 int
 9 获取所有注解
10 sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl
11 sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl
12 sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl
13 获取完整参数信息
14 参数修饰符:0参数名:arg0参数类型:java.lang.String
15 参数修饰符:0参数名:arg1参数类型:java.lang.String
16 参数修饰符:0参数名:arg2参数类型:int
17 namezhangsan    pwd123
18 java.lang.NullPointerException
19 java.lang.IllegalArgumentException
20 java.lang.Deprecated

 

转载于:https://www.cnblogs.com/zhengzuozhanglina/p/11219844.html

反射Method使用可以通过以下步骤: 1. 获取Class对象:首先需要获取要反射的Class对象,可以通过名调用Class.forName()方法或者使用的class属性获取。 2. 获取Method对象:接下来需要获取要反射的方法的Method对象,可以通过Class对象的getMethod()、getDeclaredMethod()、getMethods()、getDeclaredMethods()等方法获取。 3. 设置方法可访问性:如果要反射的方法是私有的,需要设置方法的可访问性为true,否则会抛出IllegalAccessException异常。 4. 调用方法:最后,使用Method对象的invoke()方法调用方法,并传入方法所属的对象和方法参数,如果方法没有返回值,invoke()方法返回null,否则返回方法返回值。 以下是一个示例代码,演示了如何使用反射Method来调用一个的方法: ```java public class MyClass { private void myMethod(String str, int num) { System.out.println("My method: " + str + ", " + num); } } public class Main { public static void main(String[] args) throws Exception { MyClass obj = new MyClass(); Class<?> cls = obj.getClass(); Method method = cls.getDeclaredMethod("myMethod", String.class, int.class); method.setAccessible(true); method.invoke(obj, "Hello", 123); } } ``` 在上述示例代码中,我们首先创建了一个MyClass,并定义了一个私有的myMethod()方法。然后我们通过Class的getDeclaredMethod()方法获取了myMethod()方法的Method对象,并设置其可访问性为true。最后,我们使用Method对象的invoke()方法调用了myMethod()方法,并传入了一个字符串和一个整数作为参数。运行上述代码,输出结果为: ``` My method: Hello, 123 ``` 这说明我们成功地使用反射Method调用了一个的私有方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值