Predigest POJO in 2009

 @Author:cjcj  [email protected] <c-j.iteye.com>

最近在做WEB,觉得从JSP传值过来的POJO太繁琐...于是想用Map,但是跟"大冰块"讨论之后,Map有2个问题:

 

1,类型转换:后台取值需要做类型转换

 

2,特殊字符转换:用POJO有个好处在setXXX(xxx)方法时可以对xxx数据进行特殊处理

 

所以既不想创建很多非VO的POJO类(杂七杂八的非VO的POJO类显的代码不清晰),也想偷点懒....就设计了自己的一个存储数据的Map,不支持基本数据类型...如下,慢慢完善,欢迎大家提意见:

 

接口(为了拓展复杂数据类型):

public interface IMetadata {

	public void setValue(Object value);
	public Object getValue();
}

 基本数据存储元:

package metadata;

import java.io.Serializable;
import java.lang.reflect.Constructor;


public class Metadata implements IMetadata, Serializable, Cloneable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Indicate the meta-type
	 */
	private String type="java.lang.String";
	/**
	 * The value of the meta
	 */
	private Object value;
	

	public Metadata(Object value,String type){
		this.type=type;
		this.value=value;
	}
	public Object getValue() {
		// TODO Auto-generated method stub
		if(value==null)return null;
		return cast();
		
	}
	private Object cast(){
		try {
			Class cls;
			cls = Class.forName("java.lang."+type);	
			if(cls.isInstance(value))return value;
			if(cls.isPrimitive())return value;
			Constructor result=cls.getConstructor(new Class[]{String.class});
			return result.newInstance(new Object[]{value.toString()});
		}catch (Exception e) {
			throw new IllegalArgumentException("无法转化[" + type + "]为类型");
		}
	}
	public void setValue(Object value) {
		this.value=value;
		// TODO Auto-generated method stub
		
	}

}

 

 

 

 

重载HashMap类:

import java.util.HashMap;

public class MetaMap extends HashMap{
	
	 /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Object get(Object key) {
		 Metadata result=(Metadata) super.get(key);
		 return result.getValue();
	 }
	public Object put(Object key, Object value,String type){
		return super.put(key, new Metadata(value,type));
	}
	public Object put(Object key,Object value){
		return super.put(key, new Metadata(value,"String"));
	}
}

 

 

 

测试代码:

package metadata;

import java.util.Map;

public class MetaTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map map=new MetaMap();
		Integer aa=new Integer(23);
		map.put("数据一", aa);
		map.put("数据二", 3242.432);
		Integer num= (Integer) map.get("数据一");
		if(num instanceof Integer){
			System.out.println(num);
		}
		Float fl= (Float) map.get("数据二");
		if(fl instanceof Float){
			System.out.println(fl);
		}
	}

}

 

 

 

你可能感兴趣的:(java,jsp,Web,J#,Gmail)