1. package com.atguigu.java3;
    2. import com.atguigu.java2.Person;
    3. import org.junit.Test;
    4. import java.lang.annotation.Annotation;
    5. import java.lang.reflect.Method;
    6. import java.lang.reflect.Modifier;
    7. /**
    8. * @author Dxkstart
    9. * @create 2021-06-07 18:46
    10. */
    11. public class MethodTest {
    12. @Test
    13. public void test1(){
    14. Class<Person> clazz = Person.class;
    15. //getMethod():获取当前运行时类及其所有父类中声明为public权限的方法
    16. Method[] methods = clazz.getMethods();
    17. for(Method m :methods){
    18. System.out.println(m);
    19. }
    20. System.out.println("*************");
    21. //getDeclaredMethods():获取当前运行时类中声明的所有方法。(不包含父类中声明的方法)
    22. Method[] declaredMethods = clazz.getDeclaredMethods();
    23. for(Method ms:declaredMethods){
    24. System.out.println(ms);
    25. }
    26. }
    27. /*
    28. @Xxxx
    29. 权限修饰符 返回值类型 方法名(参数类型1 形参名,。。。) throws XxxxException{}
    30. */
    31. @Test
    32. public void test2(){
    33. Class<Person> clazz = Person.class;
    34. Method[] declaredMethods = clazz.getDeclaredMethods();
    35. for(Method m:declaredMethods) {
    36. //1.获取方法声明的注解
    37. Annotation[] annos = m.getAnnotations();
    38. for(Annotation a: annos){
    39. System.out.println(a);
    40. }
    41. //2.权限修饰符
    42. System.out.print(Modifier.toString(m.getModifiers()) + "\t");
    43. //3.返回值类型
    44. System.out.print(m.getReturnType().getName() + "\t");
    45. //4.方法名
    46. System.out.print(m.getName());
    47. System.out.print("(");
    48. //5.形参列表
    49. Class<?>[] parameterTypes = m.getParameterTypes();
    50. if( !(parameterTypes == null && parameterTypes.length ==0)){
    51. for (int i = 0; i < parameterTypes.length; i++) {
    52. System.out.print(parameterTypes[i].getName() + " args_" + i);
    53. }
    54. }
    55. System.out.print(")");
    56. //6.抛出的异常
    57. Class[] exceptionTypes = m.getExceptionTypes();
    58. if (exceptionTypes.length > 0){
    59. System.out.println("throws ");
    60. for(int i = 0;i < exceptionTypes.length;i++){
    61. if(1 == exceptionTypes.length - 1) {
    62. System.out.println(exceptionTypes[i].getName());
    63. break;
    64. }
    65. System.out.println(exceptionTypes[i].getName() + ",");
    66. }
    67. }
    68. System.out.println();
    69. }
    70. }
    71. }