java反射机制实现getter setter

//实体类对象

package com;

public class Persion {
private String name1;
private String name2;
private String name3;
private String name4;
private String name5;
private String name6;
private String name7;
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
public String getName3() {
return name3;
}
public void setName3(String name3) {
this.name3 = name3;
}
public String getName4() {
return name4;
}
public void setName4(String name4) {
this.name4 = name4;
}
public String getName5() {
return name5;
}
public void setName5(String name5) {
this.name5 = name5;
}
public String getName6() {
return name6;
}
public void setName6(String name6) {
this.name6 = name6;
}
public String getName7() {
return name7;
}
public void setName7(String name7) {
this.name7 = name7;
}

}


测试方法及工具类:

package com;
import java.lang.reflect.Method;
public class mainTest {
//setter方法注入
private static void setter(Object obj, String att, Object value, Class type) {
try {
StringBuilder sb = new StringBuilder();
sb.append("set").append(att.substring(0, 1).toUpperCase()).append(att.substring(1));
Method met = obj.getClass().getMethod(sb.toString(), type);
met.invoke(obj, value);
} catch (Exception e) {
e.printStackTrace();
}
}

//getter方法注入
private static Object getter(Object obj, String att) {
Object temp=null;
try{
StringBuilder sb = new StringBuilder();
sb.append("get").append(att.substring(0, 1).toUpperCase()).append(att.substring(1));
            Method met = obj.getClass().getMethod(sb.toString());
            temp = met.invoke(obj);
        }catch(Exception e){
            e.printStackTrace();
        }
return temp;
}


public static void main(String[] args) {
Persion per = new Persion();
System.out.println("setter开始。。。。。");
for(int i=1;i<8;i++){
setter(per, "name"+i, "name"+i, String.class);
}
System.out.println("setter结束。。。。。");
System.out.println("getter开始。。。。。");
for(int i=1;i<8;i++){
Object obj= getter(per, "name"+i);
System.out.println(obj);
}
System.out.println("getter结束。。。。。");
}
}

你可能感兴趣的:(java反射机制实现getter setter)