Generics in static methods

后端 未结 2 837
Happy的楠姐
Happy的楠姐 2021-01-24 10:42

I need to add a method in a utility class with some static methods that parses things from a JSON string and returns an array of things.

Problem is that there are variou

相关标签:
2条回答
  • 2021-01-24 10:44

    You need to pass it.

    public static <E extends Thing> E[] parseThingsFromJSON(String body, Class<E[]> eClass) {
        return parser.fromJson(body, eClass);
    }
    

    Generics is largely a compile time feature. This means its not available at runtime (with some exceptions)

    In this case, to make to make the generic type available at runtime, you have to pass it as an additional argument.

    0 讨论(0)
  • 2021-01-24 11:00

    From memory this is a similar problem to what you have when using Arrays.asList()

    With this you do

    Arrays.<MyOjbect>(new MyObject(), new MyObject());
    

    or in your specific case where you are passing an array eg

    Arrays.<Integer[]>asList(new Integer[]{new Integer(1)});
    

    The signature in the JDK for this method is

    public static <T> List<T> asList(T... a){...}
    

    which is similar to your I think

    0 讨论(0)
提交回复
热议问题