转载请注明来自我的CSDN博客:黄朝辉的博客
首先,我们看一下什么是反射,以下Oracle官网上对反射的说明:
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.
译:反射通常被用在那些需要能检查或者修改运行在Java虚拟机中应用程序的运行时行为的程序中。这是一个相对高级的特性,应该只被那些对该语言的基本原理有着比较深的理解的开发者所使用。注意以上警告,反射是一个有力的技术,能用来进行一些其它技术实现不了的操作。(翻译得比较渣,大神勿怪啊)
下面我们通过反射来实现在外部类中调用其它类的私有方法。
我们在Main类的main方法里来,来调用ReflectionTester类的print方法。
以下是ReflectionTester类,我们可以看见里面只有一个私有的print方法。
ReflectionTester类
package cn.sehzh;
public class ReflectionTester {
private void print()
{
System.out.println("private print method was called!");
}
}
Main类
package cn.sehzh;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
try {
//获得ReflectionTester类
Class c = Class.forName("cn.sehzh.ReflectionTester");
//获得ReflectionTester的构造器
Constructor ct = c.getConstructor(null);
//创建ReflectionTester类的一个实例
Object test = ct.newInstance(null);
//获得print方法
Method printMethod = c.getDeclaredMethod("print", null);
//允许私有方法的调用
printMethod.setAccessible(true);
//调用test对象的print方法
printMethod.invoke(test, null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果:
注意:
//获得print方法
Method printMethod = c.getDeclaredMethod("print", null);
这里不能使用getMethod方法,getMethod方法对私有方法没用。
//允许私有方法的调用
printMethod.setAccessible(true);
必须要加上这一句才能调用私有方法。