简体   繁体   English

Java - 将类型传递给超类静态方法

[英]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. 我的项目中有多个pojo类,我希望能够将每个对象序列化为json。 So I created new Serializer class (gson used to serialize): 所以我创建了新的Serializer类(用于序列化的gson):

public class Serializer
{
    public String toJson()
    {
        return new Gson().toJson(this);
    }
}

And my example class extends Serializer : 我的示例类扩展了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: 我可以通过调用toJson方法序列化任何扩展Serializer的类的对象,如下所示:

TestClass test1 = new TestClass();
String json =  test1.toJson();

Now I want construct class object by calling static method fromJson . 现在我想通过从fromJson调用静态方法fromJson构造类对象。 So my TestClass looks like this: 所以我的TestClass看起来像这样:

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. 当然,这不是好方法,因为我需要在我的所有类中包含fromJson实现。

Question: how to move fromJson to superclass ( Serializer ), and provide single, type dependent implementation for fromJson method? 问题:如何从fromJson移动到超类( Serializer ),并为fromJson方法提供单一的,类型相关的实现?

You can define static fromJson() method in Serializer base class: 您可以在Serializer基类中定义静态fromJson()方法:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM