Search code examples
javagenericsnested-generics

Inferring type from generic


Is there any way to infer the type of the object O as in the example below (which will not compile):

public interface LogUpdateListener<S extends LogSet<O>> {
    void logUpdated(O object);
}

So in the example above LogSet is generic taking an O where O extends LogObject. If S extends LogSet, then using S is it possible to infer the type of O to use as the type for the logUpdated method?

Is the only way to do this explicitly like this:

public interface LogUpdateListener<O extends LogObject, S extends LogSet<O>>

I hope my question makes sense.


Solution

  • I'm not sure I have understood your question, but if you are asking:

    1. How do I declare a LogUpdateListener ...
    2. of type S which extends "LogSet of type O", ...
    3. where type O extends LogObject?

    then, yes, you declare it as:

    public interface LogUpdateListener<O extends LogObject, S extends LogSet<O>>
    

    This is because if O is a type parameter (which is what I think you are saying), then you need to declare it in the type parameter section. If you also want to bound O to be of a subtype of LogObject, you need to add that bound along with the type parameter declaration.

    However, you should remember that:

    • for a type P where P is a proper subtype of O (P < O)
    • LogSet<P> is not a subtype of LogSet<O>

    This may mean you need to use wildcard parameterized types of LogSet<? extends O> or LogSet<? super O> in your method declarations if, for example, you wanted to copy from/to (in that order) other LogSet objects.