两个对象之间根据属性名拷贝

// TODO 放软应用,以及以下代码应该发在公共的工具类中
	//缓存存放类的field信息
	private static Map<Class<?>, Map<String, Field>> fieldsCache = new HashMap<Class<?>,  Map<String, Field>>();
	private ReadWriteLock rw = new ReentrantReadWriteLock();

	private  Map<String, Field> getAllFieldsOfClass(Class<?> cls) {
		rw.readLock().lock();
		 Map<String, Field> fieldmap = null;
		try {
			fieldmap = fieldsCache.get(cls);
			if (fieldmap == null) {
				rw.readLock().unlock();
				rw.writeLock().lock();
				try {
					if (fieldmap == null) {
						fieldmap = new HashMap<String, Field>();
						Class<?> itr = cls;
						while ((null != itr) && !itr.equals(Object.class)) {
							Field[] declaredFields = itr.getDeclaredFields();
							if(declaredFields != null && declaredFields.length > 0){
								for(Field f : declaredFields){
									String fieldName = f.getName();
									if(fieldmap.get(fieldName) == null && !"serialVersionUID".equals(fieldName)
											&& !Modifier.isStatic(f.getModifiers())){
										fieldmap.put(fieldName, f);
										f.setAccessible(true);
									}
								}
							}
							itr = itr.getSuperclass();
						}
						fieldsCache.put(cls, fieldmap);
					}
				} finally {
					rw.writeLock().unlock();
				}
				rw.readLock().lock();
			}
		} finally {
			rw.readLock().unlock();
		}
		return fieldmap;
	}

	// TODO 放util类中
	private <T, R> R simpleConvertType(T t, Class<R> clazz) throws Exception {
		if (t == null)
			return null;
		Map<String, Field> fromFieldMap = getAllFieldsOfClass(t.getClass());
		R target = clazz.newInstance();
		Map<String, Field> toFieldMap = getAllFieldsOfClass(clazz);
		for(Map.Entry<String, Field> en : toFieldMap.entrySet()){
			String fieldName = en.getKey();
			Field valueField = fromFieldMap.get(fieldName);
			if(valueField != null){
				en.getValue().set(target, valueField.get(t));
			}
		}
		return target;
	}

你可能感兴趣的:(java)