Search code examples
javajsongenericsinheritancetype-erasure

Fixing "has the same erasure as..but does not override" for subclass w/ same method signature but new implementation?


In java I have a class which extends JsonProvider.java as RootlessJsonProvider.java that allows the class to work with JSON without a root element.

I'm attempting to override the method readFrom which is still defined with the exact same method signature as the class that implements it:

    @Override
    public Object readFrom(final Class<Object> type, final Type genericType,
            final Annotation[] anns, final MediaType mtype,
            final MultivaluedMap<String, String> headers,
            final InputStream inputStream) {

        InputStream inputStreamNew = null;

        if (type != null) {
            final XmlRootElement rootElement = type
                    .getAnnotation(XmlRootElement.class);
            if (rootElement != null) {
                inputStreamNew = transformStreamForDropRootElement(rootElement,
                        inputStream);
            }
        }

        return super.readFrom(type, genericType, anns, mtype,
                headers, inputStreamNew);
    }

But all that's changed is the implementation, to allow rootless json usage.

The error that comes with it is:

The method readFrom(Class<Object>, Type, Annotation[], MediaType, MultivaluedMap<String,String>, InputStream) of type RootlessJsonProvider has the same erasure as readFrom(Class, Type, Annotation[], MediaType, MultivaluedMap, InputStream) of type MessageBodyReader but does not override it

Changing the method name also doesn't work because it's usage is off the implementation.

i.e.

JsonProvider rootlessProvier = new RootlessJsonProvder();

rootlessProvider.rootlessReadFrom(....); //ERROR <---- this method doesn't exist as it's not defined in JsonProvider.java

There aren't any parameters based on how this method is used that's less generic of a type, so how can I resolve this error?

Edit:

JsonProvider.java

part of cxf-jaxrs version 3.1.5


Solution

  • The function signature is

    class JsonProvider<T> {
        T readFrom(Class<T> ...) {
        }
    }
    

    You need to extend the class properly.

    class RootlessJsonProvider extends JsonProvider<SomeClassOfOurs> {
        @Override
        SomeClassOfOurs readFrom(Class<SomeClassOfOurs> ...) {
        }
    }
    
    JsonProvider<SomeClassOfOurs> rootlessProvider = new RootlessJsonProvider(...);
    

    Or,

    class RootlessJsonProvider<T> extends JsonProvider<T> {
        @Override
        T readFrom(Class<T> ...) {
        }
    }
    
    JsonProvider<SomeClassOfOurs> rootlessProvider = new RootlessJsonProvider<>(...);