Issue
I have the following classes:
import lombok.Data;
import java.io.Serializable;
@Data
public class Person implements Serializable {
private String age;
}
Main Application
import org.apache.commons.lang3.SerializationUtils;
public class MainApp {
public static void main(String[] args) {
Person v = new Person() {{
setAge("SD");
}};
Person person2 = SerializationUtils.clone(v);
}
}
Test Class
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
public class TestClass {
@Test
public void test() {
Person v = new Person() {{
setAge("SD");
}};
Person person2 = SerializationUtils.clone(v);
}
}
In the main application the serialization works and in the unit test it doesn't. It throws SerializationException with the following details: org.apache.commons.lang3.SerializationException: java.io.NotSerializableException: com.mypackage.TestClass
I'm using intellij and the project is maven project and the tests are JUnit4. dependency version:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
Please advise how can I solve it?
Solution
You are declaring an anonymous class in the test.
Anonymous classes in non-static scopes (in an instance method, constructor, instance initializer, or instance member initializer) implicitly enclose a reference to the enclosing class (in this case, TestClass
).
As that class isn't serializable, it can't be serialized.
Declare your anonymous subclass as a static class instead.
public class TestClass {
@Test
public void test() {
Person v = new TestPerson();
Person person2 = SerializationUtils.clone(v);
}
static class TestPerson extends Person {
{
setAge("SD");
}
}
}
Or, better, don't use double-brace initialization, especially if you don't understand the problems it causes with respect to serialization (as well as other problems):
Person v = new Person();
v.setAge("SD");
Person person2 = SerializationUtils.clone(v);
Answered By - Andy Turner