标签: classcastexception

如何使用 Jackson 将 JSON 对象键解析为整数?

我正在将 JSON 反序列化为Map<Integer, String>.

但我正在逐渐上述ClassCastException -如果我尝试指派key到原始int

ObjectReader reader = new ObjectMapper().reader(Map.class);
String patternMetadata = "{\"1\":\"name\", \"2\":\"phone\", \"3\":\"query\"}";
Map<Integer, String> map = reader.readValue(patternMetadata);
System.out.println("map: " + map);
for (Map.Entry<Integer, String> entry : map.entrySet())
{
    try
    {
        System.out.println("map: " + entry.getKey());
        int index = entry.getKey();
        System.out.println("map**: " + index);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integertry块中的第二行收到此异常。

我什至尝试改变int index = enty.getKey().intValue(). 但仍然发生相同的异常。

PS:我正在使用 …

java json coercion classcastexception jackson

2
推荐指数
1
解决办法
1534
查看次数

如何修复错误“无法转换为 com.sun.speech.freetts.VoiceDirectory”?

我尝试在我的java程序中使用FreeTTS(来自https://freetts.sourceforge.io/docs/index.php),但收到此错误:java.lang.ClassCastException: com.sun.speech.freetts.en.us.cmu_time_awb.AlanVoiceDirectory cannot be cast to com.sun.speech.freetts.VoiceDirectory

我尝试将免费 TTS jar 文件重新添加到我的项目中,这是我的代码:

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class TextToSpeech {
//String voiceName = "kevin16";
VoiceManager freeVM;
Voice voice;
public TextToSpeech(String words) {
    freeVM = VoiceManager.getInstance();
    voice = VoiceManager.getInstance().getVoice("kevin16");
    if (voice != null) {
        voice.allocate();//Allocating Voice
    }

    try {
        voice.setRate(190);//Setting the rate of the voice
        voice.setPitch(150);//Setting the Pitch of the voice
        voice.setVolume(3);//Setting the volume of the voice
        SpeakText(words);// Calling speak() method


    } catch (Exception e1) {
        e1.printStackTrace();
    }



} …
Run Code Online (Sandbox Code Playgroud)

java classcastexception freetts

2
推荐指数
1
解决办法
2601
查看次数

为什么“java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to”有界类型参数错误而不是形式类型参数错误?

由于 java 没有通用数组,我使用了将 Object 数组转换为类型参数的常规技巧。当我有一个正式的类型参数时,这工作正常,<T>但当我使用有界类型参数时则不然<T extends something>

使用正式类型的以下代码工作正常

public class Deck <T> {
    private T [] cards;
    private int size;

    public Deck () {
        cards = (T []) new Object[52];
        size = 0;
    }
}

public class BlackJackGame {
    Deck<BlackJackCard> deck;

    public BlackJackGame() {
        deck = new Deck<>();
        populate (deck);
        deck.shuffle();
    }
}

public class BlackJackCard extends Card {
}
Run Code Online (Sandbox Code Playgroud)

以下使用有界类型的代码抛出错误

public class Deck <T extends Card> {
    private T [] cards;
    private int size;

    public …
Run Code Online (Sandbox Code Playgroud)

java generics classcastexception

2
推荐指数
1
解决办法
2172
查看次数

将数组存储在变量中时出现 Kotlin ClassCastException

我创建了一个 RollingWindow 类,以便将固定数量的最新数据点存储在数组中。

class RollingWindow<T> (private val length: Int) {

    private val window = Array<Any?>(length) {null}
    private var count = 0


    fun push(t: T) {
        if (length == 0)
            return

        window[currentIndex()] = t
        count++
    }

    @Suppress("UNCHECKED_CAST")
    fun toArray(): Array<T> {
        if (length == 0)
            return arrayOf<Any>() as Array<T>

        val firstHalf = window
            .copyOfRange(currentIndex(), window.size)
            .filterNotNull()
            .toTypedArray()
        val secondHalf = window
            .copyOfRange(0, currentIndex())
            .filterNotNull()
            .toTypedArray()
        
        val arr = arrayOf(*firstHalf, *secondHalf) as Array<T>
        print(arr.contentToString()) 
        //this works fine but for some reason the …
Run Code Online (Sandbox Code Playgroud)

arrays generics classcastexception kotlin

2
推荐指数
1
解决办法
329
查看次数

为什么只在访问返回值时抛出ClassCastException?

此问题相关

鉴于此功能:

public static <S extends CharSequence> S foo(S s) {
  return (S) new StringBuilder(s);
}
Run Code Online (Sandbox Code Playgroud)

为什么这个调用会毫无例外地执行:

foo("hello");
Run Code Online (Sandbox Code Playgroud)

但是这个抛出ClassCastException?

System.out.println(foo("hello"));
Run Code Online (Sandbox Code Playgroud)

java classcastexception

1
推荐指数
1
解决办法
286
查看次数

奇怪的运行时错误(声明时ClassCastException)

我正在制作的程序中有以下代码:

01  public class Clazz<T>
02  {
03    T[] t;
04    
05    public Clazz<T> methodA(int... ints)
06    {
07      Clazz<Integer> ints2 = new Clazz<>();
08      int remInd[] = new int[t.length - ints2.t.length];
09      return this;
10    }
11  }
Run Code Online (Sandbox Code Playgroud)

但是当我运行方法时methodA,我收到此错误:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
    at Clazz.methodA(Clazz.java:8)
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此错误?当然,与所讨论的巨大类相比,我所显示的代码是不完整的(例如,t在检查其长度时,数组不会为空),但我相信我已经展示了重要的一切.这为什么不运行?

注意:我使用JDK 1.7进行此操作,这就是为什么第7行编译和工作的原因

工作方案


无论出于何种原因,我决定实施以下解决方案,并且它有效:

01  public class Clazz<T>
02  {
03    T[] t;
04    
05    public Clazz<T> methodA(int... ints)
06    { …
Run Code Online (Sandbox Code Playgroud)

java classcastexception

1
推荐指数
1
解决办法
795
查看次数

转换为已实现的类

所以,我正在使用Java,尝试将一个类型转换java.sql.ResultSet为我自己的类MyResultSet

这是代码:MyResultSet.java

public class MyResultSet implements java.sql.ResultSet{
     //There are a bunch of Implemented Methods here. None of them have any custom code, They are all unchanged. Just didn't want to put huge code in here.
}
Run Code Online (Sandbox Code Playgroud)

我试图用它来代码的代码

ResultSet r = getResultSet();
return (MyResultSet)r;
Run Code Online (Sandbox Code Playgroud)

每当我运行它,我得到一个"ClassCastException".

有人可以向我解释如何投射到已实施的类吗?

java class classcastexception

1
推荐指数
1
解决办法
1105
查看次数

clojure代码给出错误:java.lang.Integer无法强制转换为clojure.lang.IFn

嗨,我有这个学校项目,我差不多完成了所以我不需要代码的帮助,问题是我从来没有在clojure中编码但是为了这个任务必须尝试并使用绑定表单捕获clojure中的宏,有一些REPL命令可以为赋值传递给出不同的响应,

无论如何我得到一个错误,我一直在谷歌搜索,但没有任何具体的这个问题和大多数解释基本上需要有自己的解释似乎没有什么似乎是初学者适应所以它对我没有多大帮助.

(defmacro safe [bindings & code]
(if (list? bindings)
`(try 
   ~bindings 
  (catch Throwable except# except#)) 

(if (= (count bindings) 0)
  `(try ~code 
     (catch Throwable except# except#)) 

  `(let ~(subvec bindings 0 2)

     (try
       (safe ~(subvec bindings 2) ~@code)
       (catch Throwable except# except#) 

       (finally
         (. ~(bindings 0) close))))))) ;;safe



(def divider(safe (/ 1 0)))
(def reader (safe [s (FileReader. (java.io.File. "C:/text.txt"))] (. s read)))
Run Code Online (Sandbox Code Playgroud)

所以我得到的错误是

=> (def v (safe [s (FileReader. (java.io.File. "C:/text.txt"))] (. s read)))
#'myProject.core/v
=> v
#<ClassCastException java.lang.ClassCastException: …
Run Code Online (Sandbox Code Playgroud)

clojure classcastexception

1
推荐指数
1
解决办法
1229
查看次数

java.lang.ClassCastException:java.util.HashMap无法强制转换为java.util.TreeMap

我将TreeMap填充到intent中:

private TreeMap<Long, Long> mSelectedItems;

...

mSelectedItems = new TreeMap<Long, Long>();

...

Intent intent = new Intent();
intent.putExtra("results", mSelectedItems);

setResult(RESULT_OK, intent);
Run Code Online (Sandbox Code Playgroud)

然后尝试在调用活动中将其读回:

TreeMap<Long, Long> results = (TreeMap<Long, Long>)
    data.getSerializableExtra("results");
Run Code Online (Sandbox Code Playgroud)

什么导致:

E/AndroidRuntime(26868): Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.TreeMap
Run Code Online (Sandbox Code Playgroud)

嗯,当然,但是因为我没有在代码中的任何地方使用HashMap,并且因为TreeMap实现了Serializable,所以这应该没有错误,不是吗?为什么android试图强迫我上课我不使用?

android hashmap treemap classcastexception android-intent

1
推荐指数
1
解决办法
6461
查看次数

java.lang.ClassCastException:org.apache.xerces.jaxp.SAXParserFactoryImpl无法转换为javax.xml.parsers.SAXParserFactory

我正在尝试在JBoss AS 6.1.0.Final上部署PrimeFaces 5.3展示WAR。 http://repository.primefaces.org/org/primefaces/showcase/5.3/showcase-5.3.war

通过进行此处建议的2个更改,我可以将其部署在JBoss AS 7.1.1.Final上:http : //forum.primefaces.org/viewtopic.php? f=23&t=41278#p130047

1)从web.xml中删除侦听器:

<listener>
  <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

2)从WEB-INF / lib删除javax.faces-2.2.8.jar

但是当我在JBoss 6.1.0.Final上部署相同的经过修改的JAR时,我得到了2个类强制转换异常。

我希望当它在JBoss 7.1上运行时,我可以在6.1上运行,因为它们都是JEE6。

可悲的是我必须使用JBoss 6.1,因为我依赖于JBoss ESB。

任何建议表示赞赏...

ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/showcase-5.3.fixed]] Exception sending context initialized event to listener instance of class org.jboss.web.jsf.integration.config.JBo ssMojarra20ConfigureListener: java.lang.ClassCastException: Cannot cast org.hibernate.validator.util.LazyValidatorFactory to javax.validation.ValidatorFactory
        at java.lang.Class.cast(Class.java:3133) [:1.7.0_67]
        at org.jboss.deployers.spi.attachments.helpers.AbstractAttachments.getAttachment(AbstractAttachments.java:49) [:2.2.2.GA]
        at org.jboss.deployers.spi.attachments.helpers.AbstractAttachments.getAttachment(AbstractAttachments.java:56) [:2.2.2.GA]
        at org.jboss.mc.servlet.vdf.api.BaseAttachmentVDFConnector.lookup(BaseAttachmentVDFConnector.java:74) [:2.2.0.GA]
        at org.jboss.mc.servlet.vdf.api.BaseAttachmentVDFConnector.getUtilityFromAttribute(BaseAttachmentVDFConnector.java:53) [:2.2.0.GA]
        at org.jboss.mc.servlet.vdf.api.BaseAttachmentVDFConnector.getUtilityFromAttribute(BaseAttachmentVDFConnector.java:35) [:2.2.0.GA]
        at org.jboss.mc.servlet.vdf.api.AbstractVDFConnector.getUtility(AbstractVDFConnector.java:93) [:2.2.0.GA]
        at org.jboss.mc.servlet.vdf.api.AbstractVDFConnector.isValid(AbstractVDFConnector.java:78) [:2.2.0.GA]
        at org.jboss.web.jsf.integration.config.JBossJSFInitializer.addBeanValidatorFactory(JBossJSFInitializer.java:65) [:1.0.3]
        at org.jboss.web.jsf.integration.config.JBossMojarra20ConfigureListener.doVersionSpecificInitialization(JBossMojarra20ConfigureListener.java:37) [:1.0.3]
        at org.jboss.web.jsf.integration.config.JBossMojarraConfigureListener.contextInitialized(JBossMojarraConfigureListener.java:56) [:1.0.3] …
Run Code Online (Sandbox Code Playgroud)

jsf jaxp classcastexception primefaces jboss6.x

1
推荐指数
1
解决办法
4319
查看次数