ParamConverterProvider方法返回类型不匹配

时间:2014-06-17 05:08:14

标签: jax-rs java-7 eclipse-kepler jersey-2.0

在下面的代码段中,我在Provider类中继续收到以下错误。

  

类型不匹配:无法从DemoParamConverter转换为   ParamConverter

package com.ofss.shop.application.translators;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.Provider;

@Provider
public class DemoParamConverterProvider {

    private final DemoParamConverter dpc = new DemoParamConverter();

    public <T> ParamConverter<T> getConverter(Class<T> rawType,
            Type genericType, Annotation[] annotations) {

        return dpc;
    }


}

package com.ofss.shop.application.translators;
import javax.ws.rs.ext.ParamConverter;
import com.restfully.shop.domain.JavaConversionTarget;
public class DemoParamConverter implements ParamConverter<JavaConversionTarget> {

    @Override
    public JavaConversionTarget fromString(String value) {

        JavaConversionTarget jct = new JavaConversionTarget();
        jct.setJctName(value);
        return jct;
    }

    @Override
    public String toString(JavaConversionTarget value) {
        return value.toString();
    }

}

public class JavaConversionTarget {

    private String jctName;

    /**
     * @return the jctName
     */
    public String getJctName() {
        return jctName;
    }

    /**
     * @param jctName the jctName to set
     */
    public void setJctName(String jctName) {
        this.jctName = jctName;
    }

    @Override
    public String toString() {      
        return "JavaConversionTarget-toString with jctName"+ jctName;
    }

}

我正在使用Eclipse Kepler,JDK1.7,Jersey2.4。

1 个答案:

答案 0 :(得分:7)

我遇到了同样的问题,最后返回匿名ParamConverter

@Provider
public class MyConverterProvider implements ParamConverterProvider {

    @Override
    public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType,
            final Annotation[] annotations) {
        if (rawType.getName().equals(MyBean.class.getName())) {
            return new ParamConverter<T>() {

                @Override
                public T fromString(String value) {
                    MyBean myBean = new MyBean();
                    myBean.setValue(value);
                    return rawType.cast(myBean);
                }

                @Override
                public String toString(T myBean) {
                    if (myBean == null) {
                        return null;
                    }
                    return myBean.toString();
                }
            };
        }
        return null;
    }
}

如果有帮助,我推了一个例子here