Search code examples
javalistexceptionclasscastexception

java.lang.ClassCastException: myClass cannot be cast to class java.util.List


I have a class setup called MyClass that holds two lists:

public class MyClass {
    List<String> list1;
    List<Descriptor> list2;

    public List<String> getList1() { return list1; }

    public List<Descriptor> getList2() { return list2; }

    public void setList1(List<String> list1) { this.list1 = list1; }

    public void setList2(List<Descriptor> list2) { this.list2 = list2; }
}

In a different class, I want to create an object based off of MyClass and supply that object to a method

MyClass class = new MyClass();
class.setList1(someList);
class.setList2(otherList);
return Response.status(HttpStatus.OK_200).entity(class).build();

the method .entity takes an object but I get thrown the java.lang.ClassCastException error and can't figure out why.

Everything supplied is a List so I don't understand why this error is getting thrown


Solution

  • You're saying: MyClass (the entity) consists of lists, therefore it is a list.

    That's as crazy as saying: My house is made of bricks, therefore my house is a brick.

    The central job here is taking the thing you pass to the entity() method and turning that into a sack of bytes, because the HTTP protocol sends bytes. How does that work? That's where you need to learn how your tools and libraries work: I'm assuming that you're using Jersey/JAX-RS here. That is set up as follows:

    • You can send any object at all back.
    • However, that object is spooled through a bunch of registered 'translators' that each have the ability to translate a subset of object types into a stream of bytes. Out of the box, the system knows how to 'translate' Strings (that's trivial - convert the strings to bytes using .getBytes(someCharsetEncoding), voila - bytes) and a few other things. But you can add on more translators if you want. That is why the entity() method takes any Object.
    • Some registered translator assumes they are lists when they are not, causing your error. (Because you have an instance of MyClass, which isn't a list. Sure, all its fields are lists, but, a house is not a brick).

    But the solution (probably) isn't in fixing that 'translator'. First think it through: What are you actually trying to do here? HTTP just sends bytes, so what bytes do you want to send? That MyClass object needs to be turned into bytes one way or another. How should that go? What service is calling this? What does it do?

    Here's one example answer:

    Some website has javascript that makes an AJAX call to this endpoint and turns whatever it receives into a javascript object by parsing it with a JSON library, or just eval()ing it.

    If that is your answer, that you want your MyClass entity to be turned into JSON. Jackson can do that for you.