Let's say I have simple class:
public class TestClass
{
public String field1 = "Field1";
public String field2 = "Field2";
public String field3 = "Field3";
}
I have multiple pojo classes in my project and I want to be able to serialize each object to json. So I created new Serializer class (gson used to serialize):
public class Serializer
{
public String toJson()
{
return new Gson().toJson(this);
}
}
And my example class extends Serializer:
public class TestClass extends Serializer
{
public String field1 = "Field1";
public String field2 = "Field2";
public String field3 = "Field3";
}
And I am able to serialize any object of class extending Serializer by calling toJson method, like this:
TestClass test1 = new TestClass();
String json = test1.toJson();
Now I want construct class object by calling static method fromJson. So my TestClass looks like this:
public class TestClass extends Serializer
{
public String field1 = "Field1";
public String field2 = "Field2";
public String field3 = "Field3";
public static TestClass fromJson(String json)
{
return new Gson().fromJson(json, new TypeToken() {}.getType());
}
}
So, I can create new object by calling:
TestClass test2 = TestClass.fromJson(json);
Of course, this is not good approach, because I need to include fromJson implementation in my all classes.
Question: how to move fromJsonto superclass (Serializer), and provide single, type dependent implementation for fromJson method?