响应式外贸建站,学网站建设哪里好,九寨沟网站建设规划书,手机网站建设 苏州问题描述#xff1a; strut2 的织入 Session 为原始 Map 类型#xff0c;没有泛型化#xff0c;在添加属性时就会有一个恼人的警告。
功能#xff1a;
1、安全的消除警告
2、插入时检查类型#xff0c;如果不符就提前报错#xff08;免得取值时才报转换异常的错误 strut2 的织入 Session 为原始 Map 类型没有泛型化在添加属性时就会有一个恼人的警告。
功能
1、安全的消除警告
2、插入时检查类型如果不符就提前报错免得取值时才报转换异常的错误 源代码 package com.gq.util;import java.util.Map;public class SessionHelper {private Map session;private Class valueType;private SessionHelper( Map session, Class valueType ){this.session session;this.valueType valueType;}public static SessionHelper newInstance( Map session, Class valueType ){// valid parameterif( session null ){throw new NullPointerException(session cant be null, but is null.);}if( valueType null ){throw new NullPointerException(valueType cant be null, but is null.);}return new SessionHelper( session, valueType );}SuppressWarnings(unchecked)// safe cast, because just put object of calss what you want.public void putIntoSession( Object key, Object value ){// valid parameterif( key null || value null ){throw new NullPointerException(key and value must not be null.);}// valid values type weather what you wantif( value.getClass() ! valueType ){throw new RuntimeException( need class: valueType.getName() but is: value.getClass().getName() );}session.put(key, value);}}使用示例 //session.put(USER_SESSION_KEY, user);
SessionHelper.newInstance( session, User.class ).putIntoSession( USER_SESSION_KEY, user );