开发者

java generic type inference based on generic argument

开发者 https://www.devze.com 2023-01-16 04:39 出处:网络
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

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 ev开发者_开发知识库en 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消