简体   繁体   中英

How to use the generic class type parameter class

I have a genetic class parameter

public static <T> T parse(String json, Class<T> clazz) {
   T result = null;
   result = mapper.readValue(json, clazz);

   return result;
}

Let say I have a json

{
    "name": "kim"
}

How should I create the POJO for Class<T> clazz ?

public class Person<T>
{
    private T name;

    public T getName ()
    {
        return name;
    }

    public void setName (T name)
    {
        this.name = name;
    }


}

and how to pass the variable?

Person person = new Person();

parse(json, person) // ????

You can try starting from here. Rest should flow based on your requirements.

public class Person<T>
{
    private T name;
    public T getName (){
        return name;
    }

    public void setName (T name){
        this.name = name;
    }

    public static void main(String[] args){
       Person<String> p = new Person<String>();
       p.setName("Some Name");
       System.out.println(p.getName());
    }

}

See this page: https://docs.oracle.com/javase/tutorial/java/generics/types.html

Your JSON suggests that the name property of your object is a String . Therefore your object would look like

class Person {
    String name;
    // getter and setter
}

In this case there is no reason to have the POJO generic. Your last code block also suggests that this is the case. You would want to have name a generic type only if there can be different representations for it. Think of how List<T> uses its generic type. Would you want to have Person<String> , Person<StringBuilder> , Person<MyObject> all specifying different types of name ? Probably not.

The generic usage does come to play in your parse method. parse takes a JSON String and a Class type in order to tell the mapper which Java class to create from the string:

public static <T> T parse(String json, Class<T> clazz)

That is, you take a Class of type T and return an instance of T . The usage would be (instead of your last code block):

Person person = parse(json, Person.class);

where Person.class is Class<Person> , which means that the method returns as Person .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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