public class Test {
private int a;
float b;
protected double c;
public long d;
private void print(){
}
void print(int a){
}
protected void print(float a){
}
public void print(double a){
}
@org.junit.Test
public void test() throws SecurityException, NoSuchMethodException, NoSuchFieldException{
//getMethod getField方法只可以获取修饰符为public的方法 参数
// System.out.println(Test.class.getMethod("print", new Class<?>[]{}));
// System.out.println(Test.class.getMethod("print", new Class<?>[]{int.class}));
// System.out.println(Test.class.getMethod("print", new Class<?>[]{float.class}));
// System.out.println(Test.class.getMethod("print", new Class<?>[]{double.class}));
// System.out.println(Test.class.getField("a"));
// System.out.println(Test.class.getField("b"));
// System.out.println(Test.class.getField("c"));
// System.out.println(Test.class.getField("d"));
//getDeclaredMethod
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{}));
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{int.class}));
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{float.class}));
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{double.class}));
System.out.println(Test.class.getDeclaredField("a"));
System.out.println(Test.class.getDeclaredField("b"));
System.out.println(Test.class.getDeclaredField("c"));
System.out.println(Test.class.getDeclaredField("d"));
}
}
private int a;
float b;
protected double c;
public long d;
private void print(){
}
void print(int a){
}
protected void print(float a){
}
public void print(double a){
}
@org.junit.Test
public void test() throws SecurityException, NoSuchMethodException, NoSuchFieldException{
//getMethod getField方法只可以获取修饰符为public的方法 参数
// System.out.println(Test.class.getMethod("print", new Class<?>[]{}));
// System.out.println(Test.class.getMethod("print", new Class<?>[]{int.class}));
// System.out.println(Test.class.getMethod("print", new Class<?>[]{float.class}));
// System.out.println(Test.class.getMethod("print", new Class<?>[]{double.class}));
// System.out.println(Test.class.getField("a"));
// System.out.println(Test.class.getField("b"));
// System.out.println(Test.class.getField("c"));
// System.out.println(Test.class.getField("d"));
//getDeclaredMethod
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{}));
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{int.class}));
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{float.class}));
System.out.println(Test.class.getDeclaredMethod("print", new Class<?>[]{double.class}));
System.out.println(Test.class.getDeclaredField("a"));
System.out.println(Test.class.getDeclaredField("b"));
System.out.println(Test.class.getDeclaredField("c"));
System.out.println(Test.class.getDeclaredField("d"));
}
}
通过以上demo可以看出getMethod与getDeclaredMethod的区别在于,前者只可以访问public的方法,后者可以访问所有修饰符修饰的方法
原文地址:http://m.blog.csdn.net/blog/Asarja/8948894