JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制
?
?
核心代码如下:
package demo.tt;
?
import java.lang.reflect.Field;
?
public class ReflectDemo {
? ? /**
? ? ?* 在使用Flume传递数据的时候,
? ? ?* Flume传递的数据没有属性名字,只有属性值(一条记录通过分割符分割的字符串),
? ? ?* 此时唯一能够想到的方法是:
? ? ?* 方案一:拆分字符串,然后一个个赋值处理 ;
? ? ?* 方案二:使用反射实现动态赋值
? ? ?* @param args
? ? ?* @throws IllegalAccessException?
? ? ?* @throws InstantiationException?
? ? */
? ? ?@SuppressWarnings("rawtypes")
? ? ?public static void main(String[] args) throws Exception {
? ? ? ? ? ? ?String val ="001;张三;20";
? ? ? ? ? ? ?String key ="id;name;age";
?
? ? ? ? ? ? UserVO virtualUser = new UserVO();
?
? ? ? ? ? ?Class clazz = virtualUser.getClass();
? ? ? ? ? ?Object bean = clazz.newInstance();
?
? ? ? ? ? ? String[] keys = key.split(";");
? ? ? ? ? ? String[] vals = val.split(";");
?
? ? ? ? ? ? for (int i = 0; i < vals.length; i++) {
? ? ? ? ? ? ? ? ?Field field = bean.getClass().getDeclaredField(keys[i]);//int String
? ? ? ? ? ? ? ? ?field.setAccessible(true);
?
? ? ? ? ? ? ? ? ? String type = field.getType().toString();//得到此属性的类型?
? ? ? ? ? ? ? ? ? if (type.endsWith("String")) { ?
? ? ? ? ? ? ? ? ? ? ? ? ?System.out.println(field.getType()+"\t是String"); ?
? ? ? ? ? ? ? ? ? ? ?? ? ?field.set(bean,vals[i]) ; ? ? ? ?//给属性设值 ?
? ? ? ? ? ? ? ? ? ?}else if(type.endsWith("int") || type.endsWith("Integer")){ ?
? ? ? ? ? ? ? ? ? ? ? ? ?System.out.println(field.getType()+"\t是int"); ?
? ? ? ? ? ? ? ? ? ? ? ??field.set(bean,Integer.valueOf(vals[i])) ; ? ? ? //给属性设值 ?
? ? ? ? ? ? ? ? ? }else{ ?
? ? ? ? ? ? ? ? ? ? ? ? System.out.println(field.getType()+"\t"); ?
? ? ? ? ? ? ? ? ?} ?
? ? ? ? ? ? ? ? ?//System.out.println(field.getType().getSimpleName());
? ? ? ? ? ? ? }
? ? ? ? ?System.out.println(bean);
? ? ? ? }
?
? ? }
?
------------------------------------------------------------------------------------------------------------------
? ? public class UserVO {
? ? ? ? ?private int id;
? ? ? ? private String name;
? ? ? ? ? private int age;
? ? ? ?省略get/set
}
?
原文:http://gaojingsong.iteye.com/blog/2299152