您的位置:首页 > 其它

Class类中getMethods() 与getDeclaredMethods() 方法的区别

2016-08-31 22:27 405 查看
一:jdk API中关于两个方法的解释

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



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



二:代码演示

1:定义父类ReflectionParent.java

/**
*
*/
package com.paic.reflection;

/**
* @author Administrator
*
*/
public class ReflectionParent {
public void start() {
System.out.println("starting...");
}

protected void eat() {
System.out.println("eating...");
}

void end() {
System.out.println("ending...");
}

@SuppressWarnings("unused")
private void sing() {
System.out.println("sing...");
}
}


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

/**
*
*/
package com.paic.reflection;

import java.lang.reflect.Method;

import org.junit.Test;

/**
* @author Administrator
*
*/
public class ReflectionDemo1 extends ReflectionParent {

@SuppressWarnings("unused")
private void read() {
System.out.println("reading...");
}

public void write() {
System.out.println("writing...");
}

/**
* @param args
*/
@Test
public void testGetMethods() {
Method[] methods = this.getClass().getMethods();
for (Method m : methods) {
System.out.println(m.getName());
}
}

@Test
public void testGetDeclaredMethods() {
Method[] methods = this.getClass().getDeclaredMethods();
for (Method m : methods) {
System.out.println(m.getName());
}
}

}


3:运行结果

a:运行testGetMethods()方法



b:运行testGetDeclaredMethods()方法



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

1:getFileds()与getDeclaredFileds()

2:
getConstructors()与
getDeclaredConstructors()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: