简体   繁体   中英

java generic type inference based on generic argument

what I'm trying to do is send a generic method(filter) inside generic object(ItemDelegate) to another generic method(getItem). The problem is that the second method(getItem) can not infer the correct type.

// Generic object
public class ItemDelegate<T> {
    public <T> T filter() {
        return null;
    }
}

// Generic method (receiver):
public static <T> T getItem(ItemDelegate<T> delegate) {
    T item = delegate.filter();
    //... do something
    return item;
}

// Usage in code:
getItem(new ItemDelegate<String>() {
    public String filter() {
        return "Hi!";
    }
}

this code generates a compile error in getItem:

type parameters of T cannot be determined; no unique maximal instance exists for type variable T with upper bounds T,java.lang.Object

Can this even be done in java or is there a better way.

Thanks.

This works for me:

// Generic object
public class ItemDelegate<T> {
    public T filter() {
        return null;
    }

    // Generic method (receiver):
    public static <R> R getItem(ItemDelegate<R> delegate) {
        R item = delegate.filter();
        // ... do something
        return item;
    }

    public static void main(String[] args) {
        // Usage in code:
        getItem(new ItemDelegate<String>() {
            @Override
            public String filter() {
                return "Hi!";
            }
        });
    }
}

It is not clear to me what you want - do you want to make filter generic on a different parameter than that of the generic class ItemDelegate<T> ? Then I guess you should use a different parameter name as a minimum:

public class ItemDelegate<T> {
    public <U> U filter() {
        return null;
    }
}

or if you need the same parameter, don't redeclare it:

public class ItemDelegate<T> {
    public T filter() {
        return null;
    }
}

Another problem is, you don't actually override filter in your anonymous class here

getItem(new ItemDelegate<String>() {
    public String filter(ResultSet x) throws SQLException {
        return "Hi!";
    }
}

since this filter has a parameter and throws an exception.

These two issues together mean that the compiler can't infer T for ItemDelegate.filter .

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