package Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class test2 {
public static void main(String args[]) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
Person p = new Person();
Class c = p.getClass();
Method m = c.getMethod("setAge", String.class);
m.invoke(p, "21");
System.out.println("age:"+p.getAge());
}
}
class Person
{
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
问题:
1,反射机制是什么?
2,为什么要用到反射机制? 上面的例子完全可以new出来用get \ set方法来获取和定义属性值,但是用“反射”,有什么不同之处?
新手,愿听详解,谢谢!
|