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()

  • 相关阅读:
    武汉长途汽车票自动查询软件皱形(纯属练手)
    用gSOAP开发Web Service程序
    窗口的子类化与超类化
    Thunk技术
    Nokia 牵手 Windows Phone 7?
    数据库自动打包压缩工具,asp.net + ATL完美组合
    诺基亚宣布与微软达成战略合作
    DataBinder.Eval总结
    人际关系的55个绝招看完又发现,其实看不完
    .NET 中的对象序列化
  • 原文地址:https://www.cnblogs.com/warrior4236/p/5827810.html
Copyright © 2011-2022 走看看