需求说明
- 定义一个Person类,包含属性name、age。
- 使用反射的方式创建一个实例、调用构造函数初始化name、age。使用反射方式调用setName方法对姓名进
行设置,不使用setAge方法直接使用反射方式对age赋值。
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class f=Class.forName("day25.Person");
Person person= (Person) f.newInstance();
f.getMethod("setName", String.class).invoke(person,"小明");
f.getMethod("setAge", int.class).invoke(person,18);
System.out.println(person.toString());
}
输出结果:Person{name=‘小明’, age=18}