反射为单级属性赋值

简单Java类中的组成较为单一,在赋值中只需要通过反射考虑获取相应的Field与Method实例就可以实现赋值处理,课程主要讲解对于单个VO类实例化对象实现的属性赋值处理操作。

 

 1 package com.apple.demo;
 2 
 3 import java.lang.reflect.Field;
 4 import java.lang.reflect.Method;;;
 5 
 6 class ClassInstanceFactory{
 7     private ClassInstanceFactory() {}
 8     public static <T> T create(Class<?> clazz,String value) {
 9         try {
10             Object obj = clazz.getDeclaredConstructor().newInstance();
11             BeanUtils.setValue(obj, value);
12             return (T) obj;
13         } catch (Exception e) {
14             return null;
15         }
16         
17     }
18 }
19 
20 class BeanUtils{
21     private BeanUtils() {}
22     public static void setValue(Object obj, String value) {
23         String results[] = value.split("\\|");
24         for(int x=0;x<results.length;x++) {
25             String attval[] = results[x].split(":");
26             try {
27                 Field field = obj.getClass().getDeclaredField(attval[0]);
28                 Method setMethod = obj.getClass().getDeclaredMethod("set"+StringUtils.initcap(attval[0]), field.getType());
29                 setMethod.invoke(obj, attval[1]);
30             } catch (Exception e) {
31                 // TODO Auto-generated catch block
32                 e.printStackTrace();
33             } 
34         }
35     }
36 }
37 
38 class StringUtils{
39     public static String initcap(String str) {
40         if(str == null || "".equals(str)) {
41             return str;
42         }
43         if(str.length() == 1) {
44             return str.toUpperCase();
45         }else {
46             return str.substring(0,1).toUpperCase()+str.substring(1);
47         }
48     }
49 }
50 
51 class Emp{
52     private String ename;
53     private String job;
54     public String getEname() {
55         return this.ename;
56     }
57     public void setEname(String ename) {
58         this.ename = ename;
59     }
60     public String getJob() {
61         return this.job;
62     }
63     public void setJob(String job) {
64         this.job = job;
65     }
66 }
67 
68 public class JavaReflectDemo {
69     public static void main(String[] args) throws Exception{
70         String value = "ename:Smith|job:Clerk";
71         Emp emp = ClassInstanceFactory.create(Emp.class, value);
72         System.out.println("姓名:"+emp.getEname()+"、职位:"+emp.getJob());
73     }
74 }

运行结果:

姓名:Smith、职位:Clerk

 

点赞