Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - pass type to superclass static method

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<TestClass>() {}.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?

like image 680
user1209216 Avatar asked Mar 20 '19 11:03

user1209216


1 Answers

You can define static fromJson() method in Serializer base class:

public static class Serializer {
    public static <T> T fromJson(String json, Type type) {
        return new Gson().fromJson(json, type);
    }
}

And use it as:

TestClass obj = TestClass.fromJson(json, TestClass.class);

It's not perfect with redundant type information and doesn't support generics well. One should favor composition over inheritance and in this case keep serialization out of the class hierarchy. This approach has no advantage over simply:

TestClass obj = new Gson().fromJson(json, TestClass.class);
like image 165
Karol Dowbecki Avatar answered Oct 04 '22 18:10

Karol Dowbecki