// 1.定义一个标准的JavaBean,名叫Person,包含属性name、age。
// 使用反射的方式创建一个实例、调用构造函数初始化name、age,使用反射方式调用setName方法对名称进行设置,
// 不使用setAge方法直接使用反射方式对age赋值。
private static void beanDemo() throws Exception {
Class c = Class.forName(“cn.homework30.Person”);
Constructor con = c.getConstructor(String.class, int.class);
Object obj = con.newInstance(“小明”, 16);
c.getMethod(“setName”, String.class).invoke(obj, “小丽”);// 反射方式调用setName方法对名称进行设置
Field f = c.getDeclaredField(“name”);
f.setAccessible(true);
System.out.println(obj);
}
// 2. 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
public static void setProperty(Object obj, String propertyName, Object value)
throws Exception {
Class c = obj.getClass();
Field f = c.getDeclaredField(propertyName);// 获得包括私有和公有的属性
f.setAccessible(true);// 还要配合这个,取消权限检查,才能设置属性
f.set(obj, value);
System.out.println(obj);
}
// 3.编写一个类A,增加一个实例方法showString,用于打印一条字符串,在编写一个类TestA
// ,作为客户端,用键盘输入一个字符串,该字符串就是类A的全名,
// 使用反射机制创建该类的对象,并调用该对象中的方法showString
private static void showObj() throws Exception {
Scanner s = new Scanner(System.in);
System.out.println("输出一个类的全名");
Class c = Class.forName(s.nextLine());
Object obj = c.newInstance();
Method method = c.getMethod("showString");
method.invoke(obj);
}
// 4. 编写一个类,增加一个实例方法用于打印一条字符串。并使用反射手段创建该类的对象, 并调用该对象中的方法。
private static void printStr() throws Exception {
Class c = Class.forName("cn.homework30.Person");
// Person p = new Person();
Object p = c.newInstance();
Method method = c.getMethod("print");
method.invoke(p);
}