您的位置:首页 > 其它

反射的实际作用例子

2018-09-17 10:16 78 查看
[code]package utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
* 反射在实际代码中是很有用的
 * 有一个构成xml某一个节点下子节点和子节点的值的实体类,把这个实体类的属性和值放到这个节点中,如果不用反射
 * 我们就得一个一个去写,然后万一交易类型很多,这样的xml对应实体类也很多,要是每一个都去一个一个的写的话,
 * 代码是非常的臃肿的。所以我们通过反射去获取一个Object的属性和对应的值,把属性设置成子节点名称,把值设置成
 * 这个子节点的值,这是适用于任何场景的。只需要三四行代码,就可以代替n行代码。
*/
public class ObjUtils {

/**
* 得到所有类的简称
*
* @param obj
* @return
*/
public static final String getClassName(Object obj) {
return obj.getClass().getSimpleName();
}

/**
* 通过类名称查询出该类的所有属性
*
* @param className
* @return
* @throws ClassNotFoundException
*/
public static final String[] getKeysByName(String className) throws ClassNotFoundException {
Class clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new ClassNotFoundException(e.getMessage());
}
return getKeysByClass(clazz);
}

/**
* 通过class查出所有属性名称
*
* @param clazz
* @return
*/
private static final String[] getKeysByClass(Class clazz) {
Field[] fields = clazz.getDeclaredFields();
String[] keys = new String[fields.length];
for (int i = 0; i < keys.length; i++) {
keys[i] = fields[i].getName();
}
return keys;
}
[code]  /**
* 在xml节点下,把Object的所有属性,作为节点添加到element的下节点,并且对应属性的对应值也放进去
* @param element xml节点
* @param obj 对象(针对的是拼装报文时的body节点下的元素组成的实体类,注意实体类属性必须是public修饰)
*/
public static void elementInsertByDomain(Element element, Object obj) throws Exception{
Field [] fields = obj.getClass().getFields();
for(Field field : fields){
Element one = element.addElement(field.getName());
one.setText(field.get(obj)==null?"":String.valueOf(field.get(obj)));
}
}

/**
* obj是map可以获取所有key名称 obj是domian获取所有属性名称
*
* @param obj
* @return
*/
public static final String[] getKeys(Object obj) {
if (obj instanceof Map) {
Map map = (Map) obj;
Set keySet = map.keySet();
Object[] objs = map.keySet().toArray();
String[] keys = new String[objs.length];
for (int i = 0; i < keys.length; i++) {
keys[i] = objs[i].toString();
}
return keys;
} else {
return getKeysByClass(obj.getClass());
}
}

/**
* 获取对象的属性值
*
* @param obj
* @param key
* @return
*/
public static final Object getValue(Object obj, String key) {
if (obj instanceof Map) {
return ((Map) obj).get(key.toLowerCase());
} else {
String methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1, key.length());
try {
Method method = obj.getClass().getMethod(methodName, new Class[0]);
if (method == null) {
return null;
} else {
return method.invoke(obj, new Object[0]);
}
} catch (NoSuchMethodException e) {
return null;
} catch (Exception e) {
return null;
}
}
}

public static final Object setValue(Object obj, String key, Object value) {
if (obj instanceof Map) {
return ((Map) obj).put(key, value);
} else {
String methodName = "set" + key.substring(0, 1).toUpperCase() + key.substring(1, key.length());
try {
Method method = obj.getClass().getMethod(methodName, value.getClass());
return method.invoke(obj, value);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

/**
* 判断是否为空
*
* @param arg
* @return
*/
public static boolean isNull(Object arg) {
return !(arg != null && arg.toString().length() > 0);
}

/**
* 比较2个值是否一致
*
* @param obj1
* @param obj2
* @return
*/
public static boolean isSame(Object obj1, Object obj2) {
if (isNull(obj1) ^ isNull(obj2)) {
return false;
} else if (isNull(obj1) && isNull(obj2)) {
return true;
} else {
return obj1.equals(obj2);
}
}

/**
* 比较2个对象中list的属性值是否一致
*
* @param obj1
* @param obj2
* @param keys
* @return
*/
public static boolean isObjSame(Object obj1, Object obj2, List<String> keys) {
String key = new String();
for (int i = 0; i < keys.size(); i++) {
key = keys.get(i);
if (!isSame(getValue(obj1, key), getValue(obj2, key))) {
return false;
}
}
return true;
}

/**
* 获取domain对象主键数据项名称
*
* @param domain
* @return
*/
/*public static Object getKeyName(BaseDomain domain) {
if (domain.getPK().size() == 1) {
Map.Entry entry = (Entry) domain.getPK().entrySet().toArray()[0];
return entry.getKey();
} else {
return null;
}
}*/

/**
* 获取domain对象主键数据项值
*
* @param domain
* @return
*/
/*public static Object getKeyValue(BaseDomain domain) {
if (domain.getPK().size() == 1) {
Map.Entry entry = (Entry) domain.getPK().entrySet().toArray()[0];
return entry.getValue();
} else {
return null;
}
}*/

/**
* 初始化生成对象
*
* @param className
*            类名
* @return
*/
public static Object instanceObjByClassName(String className) {
try {
Class clazz = Class.forName(className);
return clazz.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return new Object();
}

public static Object byteToObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
obj = oi.readObject();
bi.close();
oi.close();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}

public static byte[] objectToByte(Object obj) {
byte[] bytes = null;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
}
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: