Double brace initialization insanity

i got blocked by a weird bug for 2 days, then later realized it might be useful for someone in future who is going to face this bug again, alright lets start with the exception.

nested exception is java.io.NotSerializableException

if you see this in your spring project and have no idea about why spring is trying to serialize your controller class, then the following contents would be relevant to your problem.

You would definitely have some kind of double brace list initialization inside your code which causes the issue, replace the double brace initialization with normal ones, then the error should be gone.

Lets see what does this evil double brace initialization does

        List<String> l1 = new ArrayList<String>();
        l1.add("bar");
        l1.add("baz");
        List<String> l2 = new ArrayList<String>(){{
            add("bar");
            add("baz");
        }};

Do you see a difference between the two blocks of code ? if you don’t dont worry, i just wanted to add extra lines for obvious reasons.

lets see the both list in debugger

The list l1 seems fine

The list l2 is weird

It is holding an reference to the the class which the list got initialized, this is causing the issue in serialization, when this data is serialized it tries to serialize the controller class which is causing an error in spring, only way to fix this problem is to remove the double brace initialization from the code, never use it again, forget it exists.