java中反射的用法

来源:互联网 发布:电脑软件不在桌面上 编辑:程序博客网 时间:2024/05/20 10:54
package test;import java.lang.reflect.Constructor;import java.lang.reflect.Method;public class ReflectionTest {public static void main(String[] args) throws Exception {String string = "hello";Class name = Class.forName("java.lang.String");Class[] parameterTypes = { String.class };// 构造方法中的参数列表Constructor constructor = name.getConstructor(parameterTypes);// 调用构造方法//Class[] methodTypes = { Integer.class };// charAt方法中的参数列表 这个地方用Integer.class 会出现“java.lang.NoSuchMethodException: java.lang.String.charAt(java.lang.Integer)”异常Class[] methodTypes = { int.class };// charAt方法中的参数列表 这个地方得用int.class,因为参数是int类型的。不明白为什么不可以用Integer.class?Method method = name.getDeclaredMethod("charAt", methodTypes);//调用String的charAt(int index)方法Object newInstance = constructor.newInstance("hello world");//实例化一个对象,用到了有参数的构造方法char c = (Character) method.invoke(newInstance, 3);//相当于 char c = newInstance.charAt(3)System.out.println("char:" + c);}}

以上是自己写的一个小例子,不知道理解的对不对,多多指教!(为什么研究这个?学IT的女朋友要毕业了,你懂得)

还有为什么要用反射,希望大家能用自己的话说一下。

0 0