Java推断类型HashSet的错误类型

编程入门 行业动态 更新时间:2024-10-26 10:29:56
本文介绍了Java推断类型HashSet的错误类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能存在重复: ,它的转换器ID为 javax.faces.Long :

< h:selectManyListbox ... converter =javax.faces.Long>

Possible Duplicate: ClassCastException when calling TreeSet<Long>.contains( Long.valueOf( someLongValue ) )

Please see the screenshot for the problem:

It seems an entry in the Typed Set cylinderIds is suddenly of type String - but how did that happen?

The bean is used from within a JSF page, but I always thought that the type system in Java should prevent this ... Any idea what is going wrong here?

Using 1.7.0_06 64 Bit on Windows 7, the application is run within a JBoss 7.1.0 on the same Java version.

解决方案

This is not exactly Java's fault. Generic type information is just lost during runtime. Java/JSF/EL does not run during compiletime, but during runtime. All it sees during runtime is a Set, not a Set<Long>.

When JSF sets submitted input values as bean properties, it retrieves them in first place as String as that's the default return type of request.getParameter(), which JSF is using under the covers to obtain request parameters. As long as no converter is specified, JSF will set those submitted String values unconverted in the Set via reflection. This is basically what is happening "under the covers":

package com.stackoverflow.q14521882; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class Test { private Set<Long> set = new HashSet<Long>(); public static void main(String[] args) throws Exception { Test test = new Test(); Field field = test.getClass().getDeclaredField("set"); Object object = field.get(test); if (object instanceof Collection) { ((Collection) object).add("string"); } System.out.println(test.set.iterator().next().getClass()); // CCE! } }

It would work when you was using Long[] instead of Set<Long>, but given that it's a Set in first place, you'd like to hold unique values only and the Long[] is therefore likely not an option. In order to solve it, you need to explicitly specify a Converter in the input component. You can use JSF builtin LongConverter for this, which has a converter ID of javax.faces.Long:

<h:selectManyListbox ... converter="javax.faces.Long">

更多推荐

Java推断类型HashSet的错误类型

本文发布于:2023-11-25 17:30:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   推断   错误   Java   HashSet

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!