如何从参数化列表中获取Class对象以输入新对象声明?

时间:2017-09-06 13:22:15

标签: java generics reflection

我重写了这行代码:

JsonResponse<LoginResult> response = new JsonResponse<>(LoginResult.class);

到此:

JsonResponse<LoginResult[]> response = new JsonResponse<>(LoginResult[].class);

因为我想传递LoginResults数组。

但是现在我想用ArrayList重写它,当然我坚持这个:

JsonResponse<List<LoginResult>> response = new JsonResponse<List<LoginResult>>(List<LoginResult>.class);

据我所知,我无法从参数化类型中获取Class对象。我阅读了很多主题如何做到但我不确定如何在我的情况下重写代码,因为我需要Class对象作为JSonResponse构造函数的输入?

public class JsonResponse<T> extends JsonRequest {

    private Type type;

    public JsonResponse(Class<T> type) {
        this.type = type;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    @SuppressWarnings("unchecked")
    public T getResult() {
        return (T) getAttribute(RESULT);
    }
}

你能帮助我或者给我一些解决这个问题的线索吗?谢谢!

2 个答案:

答案 0 :(得分:2)

您可以为此列表创建一个包装类,如:

public class LoginResultList {

    private List<LoginResult> loginResultList;

    // getters, setters etc...

}

或者您可以从ArrayList本身继承此容器类:

public class LoginResultList extends ArrayList<LoginResult> {}

答案 1 :(得分:1)

您可以从任何子类中找到JsonResponse的泛型类型参数,包括匿名类。

public class JsonResponse<T> {

  private Type type;

  public JsonResponse() {
    Class<?> curClass = this.getClass();
    if (curClass == JsonResponse.class) {
      // not a subclass with a type parameter, so assume the response
      // is just an Object.
      type = Object.class;
    }
    else {
      // in case it's not a direct subclass, search upward for JsonResponse
      while (curClass.getSuperclass() != JsonResponse.class) {
        curClass = curClass.getSuperclass();
      }

      // get the generic type information for JsonResponse
      Type responseType = curClass.getGenericSuperclass();
      if (!(responseType instanceof ParameterizedType)) {
        throw new IllegalStateException(
          "JsonResponse type definition should have been parameterized.");
      }
      Type[] responseTypeParams =
          ((ParameterizedType) responseType).getActualTypeArguments();

      // get the only type parameter, <T>
      type = responseTypeParams[0];
    }
  }

  public Type getType() {
    return type;
  }
}

现在您可以获取泛型类型信息,只要您实际将其实例化为匿名类型:

// instantiate as an anonymous subclass (the "{}")
JsonResponse<?> response = new JsonResponse<List<String>>() {};
System.out.println(response.getType());
// outputs "java.util.List<java.lang.String>"