java - 如何创建一个也处理原始 int 的 ParamConverter<Integer> ?

标签 java jakarta-ee jax-rs

所以我想创建一个自定义ParamConverter<Integer>在 jax-rs 中:

public class IntParamConverter implements ParamConverter<Integer>{

    @Override
    public Integer fromString(String value) {
        try{
            return Integer.valueOf(value);
        }catch (Exception e){
            //do some stuff
            throw new BadRequestEx("Convert Exception");
        }
    }
    @Override
    public String toString(Integer value) {
        return String.valueOf(value);
    }
}

然后我通过 ParamConverterProvider 注册它:

@Provider
public class CustomParamConverterHandler implements ParamConverterProvider {

        @Override
        public <T> ParamConverter<T> getConverter(final Class<T> rawType, Type genericType, Annotation[] annotations) {
            if (rawType.equals(Integer.class)){
                return (ParamConverter<T>) new IntParamConverter();
            }
            return null;
        }
    }

然后在资源 POJO 中使用它,如下所示:

    @GET
    @Path("/conv")
    @Produces({MediaType.TEXT_PLAIN})
    public String conv(@QueryParam("no") int no) {
        return ""+no;
    }

在运行时(使用system.out进行测试)我发现Tomee(Apache cfx?)不使用我的IntParamConverter 。如果我声明 @QueryParam("no") Integer no@QueryParam("no") int no 相反然后一切正常(tomee 使用我的自定义 paramConverter。

我尝试注册我的 IntParamConverter使用原始 int:

if (rawType.equals(int.class)){
     return (ParamConverter<T>) new IntParamConverter();
}

但是随后发生运行时异常:

java.lang.ClassCastException: Cannot cast java.lang.Integer to int
    at java.lang.Class.cast(Class.java:3369)
    at org.apache.cxf.jaxrs.utils.InjectionUtils.handleParameter(InjectionUtils.java:388)
    at org.apache.cxf.jaxrs.utils.InjectionUtils.createParameterObject(InjectionUtils.java:978)
    at org.apache.cxf.jaxrs.utils.JAXRSUtils.readQueryString(JAXRSUtils.java:1210)

如何创建这样一个处理原始 int 的 ParamConverter?

最佳答案

你不能。

Java 泛型在编译时全部转换为 java.lang.Object(通过称为类型删除的过程)。

诸如 int 之类的基本类型没有 java.lang.Object 作为其基类,因此在这种情况下不可能进行此类转换。

关于java - 如何创建一个也处理原始 int 的 ParamConverter<Integer> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34660710/

相关文章:

java - 如何在 JSP/Servlet 中执行表单验证?

java - 从代码中监控内存使用情况

java - Android:使用未经检查或不安全的操作

java - 启动先前关闭的 ExecutorService 时出现 RejectedExecutionException

java - EDT 与 Listener

java - 如何使用 Espresso 访问 RecyclerView ViewHolder?

java - Liferay 在 DLFileEntryLocalServiceUtil.addFileEntry 之后向我抛出一个 NoSuchEntryException

rest - JAX-RS/泽西客户端 : unmarshall URI encoded name/value pairs

java - 使用 Jetty : URI is too large >8192 增加限制

java - 将 JAX-RS 1.1 升级到 JAX-RS 2.0 需要有关 web.xml 部署的帮助