第四题:- package com.itheima.test;
- public class Test3 {
- // 3、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
- // public void setProperty(Object obj, String propertyName, Object value){
- // }
- public static void main(String[] args) {
- Obj obj = new Obj();
- setProperty(obj, "name", "NAME");
- setProperty(obj, "age", 22);
- System.out.println(obj.getName());
- System.out.println(obj.getAge());
- }
- public static void setProperty(Object obj, String propertyName, Object value) {
- //重构obj的propertyName的setter方法名
- propertyName = "set" + (propertyName.charAt(0) + "").toUpperCase() + propertyName.subSequence(1, propertyName.length());
- try {
- obj.getClass().getMethod(propertyName, value.getClass()).invoke(obj, value);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- class Obj {
- private String name;
- private Integer age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- }
复制代码
|