How to fix this java.lang.ClassCastException: [B cannot be cast to java.util.List

13,190

You are trying to cast your in.readObject() file to a List

This does not work in Java because the file is written as a byte[] Array data structure, not an Array List. You're going to have to convert the byte[] Array to a list before making it the value for this.list2.

Here is how you can do that:

this.list2 = Arrays.asList((byte[])in.readObject());

Array.asList() will convert your Array of byte primitives to a List (I'm assuming you're using byte primitives and not the Byte class here based on your code). It is not possible to simply cast an Array to a List in Java.

Share:
13,190
Emad
Author by

Emad

Updated on June 05, 2022

Comments

  • Emad
    Emad almost 2 years

    I'm creating a digital signature software in Java and I wanna the software to verify the message with parameters (string filename, string keyfile). But I've got this exception at line

    this.list2 = (List<byte[]>) in.readObject();

    java.lang.ClassCastException: [B cannot be cast to java.util.List. How to solve this?

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.nio.file.Files;
    import java.security.*;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    
    private boolean verifySignature(byte[] data, byte[] signature, String 
    keyFile) throws Exception {
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(getPublic(keyFile));
        sig.update(data);
    
        return sig.verify(signature);
    }
    
    public void VerifyMessage(String filename, String keyFile) throws Exception 
        {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename)))
        {
    
            this.list2 = (List<byte[]>) in.readObject();
        }
    
        lbl13.setText(verifySignature(list2.get(0), list2.get(1), keyFile) ? "VERIFIED MESSAGE" + 
          "\n----------------\n" + new String(list2.get(0)) : "Could not verify the signature.");
    }
    
  • Emad
    Emad over 5 years
    it should be byte not Byte. Thanks I got it @Mykhailo Moskura
  • Mykhailo Moskura
    Mykhailo Moskura over 5 years
    Sorry it was typo )
  • Emad
    Emad over 5 years
    It's OK I knew it and got your idea. Thanks