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("\n------------method.toString--------------");
        for (Method method1 : methods1) {
            System.out.println(method1);
        }
        System.out.println("\n");
        for (Method method2 : methods2) {
            System.out.println(method2);
        }
        System.out.println("\n------------method.getName--------------");
        for (Method method1 : methods1) {
            System.out.println(method1.getName());
        }
        System.out.println("\n");
        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:打印方法的完整签名

posted on 2016-05-05 14:55  WesTward  阅读(13662)  评论(0编辑  收藏  举报