Java(JDK1.4) Serializable 的类型转换

来源:百度知道 编辑:UC知道 时间:2024/05/13 06:48:13
Hibernate Session 的 读取API( Object get(Class clazz, Sesializable id);)
在JDK 1.5中,向这个函数传入的第二个参数是String , int ,long 都行.
但在JDK 1.4.2中,只能传入String 类型.如果数据库表的主键为int 或 long的时候,还真是一件另人头痛的事,有什么对Serializable 与 int(long)之间正确转型???
public Object getById(Class clazz, String id) {
Session session = sf.openSession();
Object obj = session.get(clazz, id);//jdk 1.4 not support
return obj;
}
sghitxia 果然是高手.
我改为这样写,
Object obj = session.get(clazz, new Integer(id));
Object obj = session.get(clazz, new Long(id));编辑器不报错了.
但是
Object obj = session.get(clazz, "1");编辑不报错.
运行是出现类型转换异常!.

再提一个问题:我函数传入id的是String 类型,为什么new Integer(id)编辑器不报错,如果id不含数字呢?会导致什么问题?(出现java.lang.NumberFormatException:)

int:Integer
long:Long
jdk1.5自动装箱,int会自转换为Integer,而Integer是实现了Serializable的,所以可以。
jdk1.4不自动装箱拆箱,所以要手动构造new Integer(int) new Long(long)

/**
* Constructs a newly allocated <code>Integer</code> object that
* represents the <code>int</code> value indicated by the
* <code>String</code> parameter. The string is converted to an
* <code>int</code> value in exactly the manner used by the
* <code>parseInt</code> method for radix 10.
*
* @param s the <code>String</code> to be converted to an
* <code>Integer</code>.
* @exception NumberFormatException if the <code>String</code> does not
* contain a parsable integer.
* @see java.lang.Integer#parseInt(java.lang.String, int)
*/
public Integer(String s) throw