zoukankan      html  css  js  c++  java
  • java的反射机制之getDeclaredMethods和getMethods的区别

    getMethods() 

              返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。注意: 返回数组中的元素没有排序,也没有任何特定的顺序。

     1 package staticMethodReflect;
     2  
     3 import java.lang.reflect.Method;  
     4   
     5 class ForMethod{  
     6       //声明静态方法  
     7       public static void sayHello(String name){  
     8            System. out.println( "你好" +name +"!!!" );  
     9      }  
    10       public String generateNum( Integer max, Integer min){  
    11             return (Math.random()*( max- min)+ min)+ "";  
    12      }  
    13 }  
    14 public class method {  
    15     
    16     public static void main(String[] args){
    17         //创建ForMethod类对象  
    18         ForMethod fm = new ForMethod();  
    19          //获取ForMethod类对象对用的Class对象  
    20          Class<?> fmc = fm.getClass();  
    21          //获取可以访问的对象的对应的Method数组  
    22         Method[] md = fmc.getMethods();  
    23         
    24         for(int i=0;i<md.length;i++){
    25             System.out.println(md[i].getName());
    26         }
    27     }
    28   }

    每次运行的结果顺序都不太一样。

    getDeclaredMethods() 

            返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。返回数组中的元素没有排序,也没有任何特定的顺序。

     1 package staticMethodReflect;
     2  
     3 import java.lang.reflect.Method;  
     4   
     5 class ForMethod{  
     6       //声明静态方法  
     7       public static void sayHello(String name){  
     8            System. out.println( "你好" +name +"!!!" );  
     9      }  
    10       public String generateNum( Integer max, Integer min){  
    11             return (Math.random()*( max- min)+ min)+ "";  
    12      }  
    13 }  
    14 public class method {  
    15     
    16     public static void main(String[] args){
    17         //创建ForMethod类对象  
    18         ForMethod fm = new ForMethod();  
    19          //获取ForMethod类对象对用的Class对象  
    20          Class<?> fmc = fm.getClass();  
    21          //获取可以访问的对象的对应的Method数组  
    22         Method[] md = fmc.getDeclaredMethods(); 
    23         
    24         for(int i=0;i<md.length;i++){
    25             System.out.println(md[i].getName());
    26         }
    27     }

    调用getDeclaredMethods只打印了本类的方法,没有打印从父类继承的方法。

    本文转自: https://blog.csdn.net/hanxueyu666/article/details/71502143

  • 相关阅读:
    【乱侃】How do they look them ?
    【softeware】Messy code,some bug of Youdao notebook in EN win7
    【随谈】designing the login page of our project
    【web】Ad in security code, making good use of resource
    SQL数据库内存设置篇
    关系数据库的查询优化策略
    利用SQL未公开的存储过程实现分页
    sql语句总结
    sql中使用cmd命令注销登录用户
    SQLServer 分页存储过程
  • 原文地址:https://www.cnblogs.com/fpqi/p/9618413.html
Copyright © 2011-2022 走看看