【问题标题】:How do I pass a class as an argument to a method? [duplicate]如何将类作为参数传递给方法? [复制]
【发布时间】:2018-03-02 04:38:53
【问题描述】:

在下面的代码中,我想将“Races.class”作为参数传递给“getAllRaces()”方法。我该怎么做?

public static void getAllRaces() throws ClientProtocolException, IOException 
{
    Response myReponse = APIExecutor.getRequest("/races");
    GsonBuilder builder  = new GsonBuilder();
    Gson gson = builder.serializeNulls().setPrettyPrinting().create();

    Races races = gson.fromJson(myReponse.getReqResponse(), Races.class);
    ...
}

【问题讨论】:

  • 有什么问题/问题?看起来你已经完成了......
  • 所有相关信息均由javadocs提供。
  • 我已经更新了我的问题。在这里,我想将 'Races.class' 作为参数传递给方法 'getAllRaces()'。

标签: java


【解决方案1】:

将您的方法更改为:

public static void getAllRaces(Class<?> clazz) {
    ...
    Races races = gson.fromJson(myReponse.getReqResponse(), clazz);
    ...
}

你可以这样称呼它:

getAllRaces(Races.class)

【讨论】:

  • 感谢@dave。这解决了我的问题
  • 没问题。乐于助人。
【解决方案2】:

Races.class 作为Class&lt;Races&gt; 类型的对象。在您的情况下,您可以使用 ? 捕获来传递未知类型的类:

public static void getAllRaces(Class<?> raceClass) {
    //...
}

【讨论】:

  • 谢谢。这解决了我的问题
猜你喜欢
  • 2012-01-11
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2021-05-19
  • 2015-12-26
  • 2020-04-07
相关资源
最近更新 更多