我正在获取类强制转换异常 如
java.lang.ClassCastException:com.model.Image无法强制转换为 java.lang.String中
下面是我从JPA实体类创建的MySQL表中获取数据的函数
public List<Image> complete(String fileName)
{
List<Image> queryResult = new ArrayList<Image>();
System.out.println("File Name is : "+fileName);
if (allImages == null)
{
System.out.println("Yeah I am coming here"+allImages);
allImages = imageFacade.findAll();
}
allImages.removeAll(servicesWithImage.getImage());
for (Image image : allImages)
{
if (image.getFileName().toLowerCase().contains(fileName.toLowerCase()))
{
queryResult.add(image);
}
}
return queryResult;
}
我已将allImages全局定义为
private List<Image> allImages;
我从p:autoComplete
Primefaces调用的上述完整方法
<p:autoComplete forceSelection="true"
minQueryLength="3"
value="#{servicesMB.image}"
label="#{msgs.image}"
required="true"
var="image"
itemLabel="#{image.fileName}"
itemValue="#{image}"
completeMethod="#{servicesMB.complete}"
dropdown="true" />
完整方法中的findAll方法如下所示:
public List<T> findAll()
{
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return em.createQuery(cq).getResultList();
}
如果我把Print Statement放在完整的方法中,我会得到所有必需的数据,但数据没有显示在p:autoComplete
上,而且我得到了ClassCastException
我将使用类似
的打印语句编辑上面的完整方法public List<Image> complete(String fileName)
{
List<Image> queryResult = new ArrayList<Image>();
if (allImages == null)
{
System.out.println("I am in If Condition");
allImages = imageFacade.findAll();
System.out.println("The Value of allImages : "+allImages);
}
System.out.println("Getter function servicesWithImage"+servicesWithImage.getImage());
allImages.removeAll(servicesWithImage.getImage());
System.out.println("allImages after removeAll method"+allImages);
for (Image image : allImages)
{
if (image.getFileName().toLowerCase().contains(fileName.toLowerCase()))
{
queryResult.add(image);
}
}
System.out.println("At the End The Value of queryResult"+queryResult);
return queryResult;
}
我的输出(仅显示方法):
02:58:56,104 INFO [stdout] (http-localhost-127.0.0.1-8080-5) I am in If Condition
02:58:56,121 INFO [stdout] (http-localhost-127.0.0.1-8080-5) The Value of allImages : [services_2.jpg, services_3.jpg]
02:58:56,122 INFO [stdout] (http-localhost-127.0.0.1-8080-5) Getter function servicesWithImage[]
02:58:56,122 INFO [stdout] (http-localhost-127.0.0.1-8080-5) allImages after removeAll method[services_2.jpg, services_3.jpg]
02:58:56,123 INFO [stdout] (http-localhost-127.0.0.1-8080-5) At the End The Value of queryResult[services_2.jpg, services_3.jpg]
02:58:56,130 SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (http-localhost-127.0.0.1-8080-5)
java.lang.ClassCastException: com.model.Image cannot be cast to java.lang.String
...帮助
答案 0 :(得分:1)
可能是由于自动完成。
自动完成就像选择一样,它不能自己管理对象,需要转换器,而且这个转换器必须能够将Image对象转换为String,并再次将此String转换为Image。
您可以在此处查看详细说明https://stackoverflow.com/a/8001418/4253629] 1