简体   繁体   中英

Generics not auto-inferring a type from “this”?

(This is with Java 7 )

I was trying to put some JSON string-generating method in my base class rather than having near-identical code in all the subclasses. The first, naive thing I tried was:

public abstract class Base
{
    [rest of class...]

    final public <T extends Base> String toJsonString() throws IOException {
        JacksonRepresentation<T> rep =
             new JacksonRepresentation<>(MediaType.APPLICATION_JSON, this);
        return rep.getText();
    }    
}

But that wouldn't compile, giving the error:

error: incompatible types
required: JacksonRepresentation<T>
found:    JacksonRepresentation<Base>
where T is a type-variable:
T extends Base declared in method <T>toJsonString()

So I tried this:

public abstract class Base
{
    [rest of class...]

    final public String toJsonString() throws IOException {
        return jsonStringHelper(this);
    }

    private static <T extends Base> String jsonStringHelper(T object)
        throws IOException {
        JacksonRepresentation<T> rep =
             new JacksonRepresentation<>(MediaType.APPLICATION_JSON, object);
        return rep.getText();
    }
}

and that worked fine. Why is that? Why can't/doesn't the compiler realize that the type of this is a type that satisfied T extends Base and do the necessary resolution?

Because you can have Class1 and Class2 that both extend base, and someone could do this:

Class1 class1 = new Class1();

String result = class1.<Class2>jsonStringHelper();

So while it is guaranteed that 'this' is a subclass of Base, there is no guarantee that 'this' is an instance of T.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM