zoukankan      html  css  js  c++  java
  • Class类中getMethods() 与getDeclaredMethods() 方法的区别

    一:jdk API中关于两个方法的解释

    1:getMethods(),该方法是获取本类以及父类或者父接口中所有的公共方法(public修饰符修饰的)

    2:getDeclaredMethods(),该方法是获取本类中的所有方法,包括私有的(private、protected、默认以及public)的方法。

    二:代码演示

    1:定义父类ReflectionParent.java

     1 /**
     2  * 
     3  */
     4 package com.paic.reflection;
     5 
     6 /**
     7  * @author Administrator
     8  * 
     9  */
    10 public class ReflectionParent {
    11     public void start() {
    12         System.out.println("starting...");
    13     }
    14 
    15     protected void eat() {
    16         System.out.println("eating...");
    17     }
    18 
    19     void end() {
    20         System.out.println("ending...");
    21     }
    22 
    23     @SuppressWarnings("unused")
    24     private void sing() {
    25         System.out.println("sing...");
    26     }
    27 }

    2:定义子类ReflectionDemo1继承父类,定义两个自己的方法和两个测试方法

     1 /**
     2  * 
     3  */
     4 package com.paic.reflection;
     5 
     6 import java.lang.reflect.Method;
     7 
     8 import org.junit.Test;
     9 
    10 /**
    11  * @author Administrator
    12  * 
    13  */
    14 public class ReflectionDemo1 extends ReflectionParent {
    15 
    16     @SuppressWarnings("unused")
    17     private void read() {
    18         System.out.println("reading...");
    19     }
    20 
    21     public void write() {
    22         System.out.println("writing...");
    23     }
    24 
    25     /**
    26      * @param args
    27      */
    28     @Test
    29     public void testGetMethods() {
    30         Method[] methods = this.getClass().getMethods();
    31         for (Method m : methods) {
    32             System.out.println(m.getName());
    33         }
    34     }
    35 
    36     @Test
    37     public void testGetDeclaredMethods() {
    38         Method[] methods = this.getClass().getDeclaredMethods();
    39         for (Method m : methods) {
    40             System.out.println(m.getName());
    41         }
    42     }
    43 
    44 }

    3:运行结果

    a:运行testGetMethods()方法

    b:运行testGetDeclaredMethods()方法

    三:其他的方法,类似字段以及构造方法和方法类似

    1:getFileds()与getDeclaredFileds()

    2:getConstructors()与getDeclaredConstructors()

  • 相关阅读:
    前端与算法 leetcode 344. 反转字符串
    JavaScript闭包使用姿势指南
    前端与算法 leetcode 48. 旋转图像
    前端与算法 leetcode 36. 有效的数独
    前端与算法 leetcode 1. 两数之和
    前端与算法 leetcode 283. 移动零
    前端与编译原理 用js去运行js代码 js2run
    前端与算法 leetcode 66. 加一
    前端与算法 leetcode 350. 两个数组的交集 II
    前端与算法 leetcode 26. 删除排序数组中的重复项
  • 原文地址:https://www.cnblogs.com/warrior4236/p/5827810.html
Copyright © 2011-2022 走看看