有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java获取当前泛型类

我看过很多关于这个论点的帖子,但这是我第一次使用泛型/反射。我想创建一些方法来包装JAX-WS调用(doPost、doGet等)

为此,JAX-WS有这样一种方法:

Integer resp = client.target(url).request().post(Entity.entity(user, MediaType.APPLICATION_JSON), Integer.class);

所以它希望最后一个参数是“返回类型”

为此,我创建了一个类来包装post mehod:

public class GenericPost<I> {
    public static I doPost(String name, Object entity) {
        String url = Constants.SERVICE_HOST_NAME + method + "/";
        Client client = ClientBuilder.newClient();  
        I resp = client.target(url).request().post(Entity.entity(entity, MediaType.APPLICATION_JSON), /* How i can tell that here i want i.class ?*/);

    return resp;
    }
}

正如我在代码中所描述的,我如何告诉该方法最后一个参数是i(泛型)类

我会这样使用这个方法:

GenericPost<Integer> postInteger = GenericPost<Integer>.doPost("something", arg);
GenericPost<String> postInteger = GenericPost<String>.doPost("something", arg);

共 (1) 个答案

  1. # 1 楼答案

    在非泛型类中创建泛型方法,并将Class<T>作为参数传递:

    public class GenericPost {
        public static <T> T doPost(String name, Object entity, Class<T> clazz) {
            String url = Constants.SERVICE_HOST_NAME + method + "/";
            Client client = ClientBuilder.newClient();  
            T resp = client.target(url).request().post(Entity.entity(entity, MediaType.APPLICATION_JSON), clazz);
            return resp;
        }
    }
    

    这样使用:

    Integer postInteger = GenericPost.doPost("something", arg, Integer.class);
    String postString = GenericPost.doPost("something", arg, String.class);