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的女朋友要毕业了,你懂得)
还有为什么要用反射,希望大家能用自己的话说一下。