zoukankan      html  css  js  c++  java
  • java反射之Class.getMethod与getDeclaredMethods()区别

    Class对象的getMethods和getDeclaredMethods都是获取类对象的方法。但是又有所不同。废话不多说, 先看demo

    package com.westward;
    
    public class Car {
        private void bell(String time){
            System.out.println("didi---"+time);
        }
        
        public void run(){
            System.out.println("running");
        }
    }

    测试代码:

    package com.westward;
    
    import java.lang.reflect.Method;
    
    public class CarTest {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Class<?> car=  Car.class;
            Method[] methods1=  car.getMethods();
            Method[] methods2= car.getDeclaredMethods();
            System.out.println("
    ------------method.toString--------------");
            for (Method method1 : methods1) {
                System.out.println(method1);
            }
            System.out.println("
    ");
            for (Method method2 : methods2) {
                System.out.println(method2);
            }
            System.out.println("
    ------------method.getName--------------");
            for (Method method1 : methods1) {
                System.out.println(method1.getName());
            }
            System.out.println("
    ");
            for (Method method2 : methods2) {
                System.out.println(method2.getName());
            }
        }
    
    }

    Output:


    ------------method.toString--------------
    public void com.westward.Car.run()
    public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
    public final void java.lang.Object.wait() throws java.lang.InterruptedException
    public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
    public boolean java.lang.Object.equals(java.lang.Object)
    public java.lang.String java.lang.Object.toString()
    public native int java.lang.Object.hashCode()
    public final native java.lang.Class java.lang.Object.getClass()
    public final native void java.lang.Object.notify()
    public final native void java.lang.Object.notifyAll()


    public void com.westward.Car.run()
    private void com.westward.Car.bell(java.lang.String)

    ------------method.getName--------------
    run
    wait
    wait
    wait
    equals
    toString
    hashCode
    getClass
    notify
    notifyAll


    run
    bell

    总结:

    getMethod():获取当前类及所有继承的父类的public修饰的方法。仅包括public

    getDeclaredMethod():获取当前类的所有方法,包括public/private/protected/default修饰的方法。

    method.getName:打印方法的名称

    method.toString:打印方法的完整签名

  • 相关阅读:
    K-lord #1
    P1220 关路灯 (区间DP)
    P1136 迎接仪式 (动态规划)
    P1063 能量项链 (区间DP)
    444 D. Ratings and Reality Shows
    P1896 [SCOI2005]互不侵犯King
    P1841 [JSOI2007]重要的城市
    P1134 阶乘问题
    P1414 又是毕业季II
    P1450 [HAOI2008]硬币购物
  • 原文地址:https://www.cnblogs.com/westward/p/5461882.html
Copyright © 2011-2022 走看看