BeanUtils

来源:互联网 发布:数据安全保密承诺书 编辑:程序博客网 时间:2024/05/21 17:09
public class BeanUtils extends org.apache.commons.beanutils.BeanUtils {


static {
ConvertUtils.register(new DateConvert(), java.util.Date.class);
ConvertUtils.register(new DateConvert(), java.sql.Date.class);
ConvertUtils.register(new DateConvert(), java.sql.Timestamp.class);
ConvertUtils.register(new BigDecimalConvert(),java.math.BigDecimal.class);
}


public static void copyProperties(Object dest, Object orig)
throws IllegalAccessException, InvocationTargetException {
org.apache.commons.beanutils.BeanUtils.copyProperties(dest, orig);
}


public static Map<String, Object> beanToMap(Object entity) {
Map<String, Object> parameter = new HashMap<String, Object>();
Field[] fields = entity.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
Object o = null;
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getMethodName = "get" + firstLetter + fieldName.substring(1);
Method getMethod;
try {
getMethod = entity.getClass().getMethod(getMethodName,
new Class[] {});
o = getMethod.invoke(entity, new Object[] {});
} catch (Exception e) {
e.printStackTrace();
}
if (o != null) {
parameter.put(fieldName, o);
}
}
return parameter;
}

}

注:属性值为null 和 “” 会不一样!

public class ContextUtils implements ApplicationContextAware{


private static ApplicationContext applicationContext;


private static final Logger logger = LoggerFactory.getLogger(ContextUtils.class);


public static ApplicationContext getApplicationContext() {
synchronized (ContextUtils.class) {
while (applicationContext == null) {
try {
ContextUtils.class.wait(60000);
if (applicationContext == null) {
logger.warn("Have been waiting for ApplicationContext to be set for 1 minute", new Exception());
}
} catch (InterruptedException ex) {
logger.debug("getApplicationContext, wait interrupted");
}
}
return applicationContext;
}
}


public static Object getBean(Class<?> beanType) {
return getApplicationContext().getBean(beanType);
}


public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}


@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
synchronized (ContextUtils.class) {
ContextUtils.applicationContext = applicationContext;
ContextUtils.class.notifyAll();
}
}


}

0 0