将Guava MultiTreemap放入http会话时出现NotSerializableException

时间:2014-10-03 18:33:16

标签: java spring-mvc serialization model-view-controller guava

我想将一个Guava TreeMultimap实例放入http会话中,但我不断收到此异常:NotSerializableException

任何人都知道怎么解决这个问题?

我的控制器看起来像这样:

@Controller
public class MyController
{

        public void doStuff(HttpServletRequest request, HttpServletResponse response)
        {

                TreeMultimap<String, MyCustomClass> myMap = TreeMultimap.create(
                     new Comparator<String>()
                     {
                          @Override
                          public int compare(String o1, String o2)
                          {
                              return o1.compareTo(o2);
                          }
                     },
                     new Comparator<MyCustomClass>()
                     {
                           @Override
                           public int compare(MyCustomClass o1, MyCustomClass o2)
                           {
                               return o1.compareTo(o2);
                           }
                      });

                      request.getSession().setAttribute("MyAttribute", myMap); //==> ERROR HERE!

          }
 }

1 个答案:

答案 0 :(得分:3)

看起来问题是您的Comparator不是Serializable。让每个人都成为实现ComparatorSerializable的非匿名类,你应该没问题。

实际上,由于你的两个Comparator都只是实现了自然排序,你应该只能写

TreeMultimap<String, MyCustomClass> myMap = TreeMultimap.create();