简体   繁体   English

泛型-调用具有泛型参数的方法

[英]Generics - Calling a method with a generic parameter

I'm struggling here with generics. 我在这里与泛型作斗争。

To start things off, I want to return a list of objects via the following callback interface: 首先,我想通过以下回调接口返回对象列表:

Callback interface: 回调界面:

public interface ArrayCallback<T> {
    public void onComplete(List<T> result);
}

So far so good. 到现在为止还挺好。 Now, using that callback, let's say I want to get a list of songs like so: 现在,使用该回调,假设我想获取类似的歌曲列表:

Using the callback to load a list of songs 使用回调加载歌曲列表

public void loadSongs(ArrayCallback<Song> callback) {
    List<Song> songs = new ArrayList<Song>();
    ...
    callback.onComplete(songs);
}

No problems here. 没问题 But now I want to load a list of SOME type of music item. 但是现在我想加载一些音乐类型的列表。 It could be songs like before, but it could be albums, artists, etc. I've called the superclass of all of these types of things MusicItem . 它可能像以前一样是歌曲,但也可能是专辑,艺术家等。我称这些类型的所有事物为MusicItem的超类。 (Thus, Song has a super class of MusicItem ) Here's where it falls over. (因此, Song具有MusicItem的超类)。

Aaaaand the following doesn't work Aaaa,以下内容无效

public void loadMusicItems(MusicItemType type, ArrayCallback<? extends MusicItem> callback) {
    switch (type) {
        case Songs:
            loadSongs(callback);
            break;
        case Albums:
            loadAlbums(callback);
            break;
        default:
            break;
}

The problem is on the loadSongs(callback) line. 问题出在loadSongs(callback)线上。 I can't call this method because the types are different. 我不能调用此方法,因为类型不同。

loadSongs(ArrayCallback<Song>) in MusicSource cannot be applied to loadSongs(ArrayCallback<capture<? extends MusicItem>>)

From my understanding I can't just use type T and need to use a wildcard because of covariance problems. 据我了解,由于协方差问题,我不能只使用T型,而需要使用通配符。

Is what I'm doing even possible? 我在做什么甚至有可能吗? After writing this question out, I suppose arguably it would look a bit strange to the compiler if I'm suddenly restricting the bounds on a method call. 写完这个问题之后,我想如果我突然限制方法调用的范围,对于编译器来说似乎有点奇怪。 I'd still be interested in working out what I'm doing wrong apart from perhaps a crazy method design. 除了可能是疯狂的方法设计之外,我仍然会对解决我正在做的事情感兴趣。

Generic type will only be applied during the compilation ( to ensure type safety ) and will disappear during the run-time. 通用类型将仅在编译期间应用(以确保类型安全),并且将在运行时消失。 So your implementation is actually violating the usage of generic type. 因此,您的实现实际上违反了泛型类型的用法。 Eg. 例如。 You can pass a Song type enum with ArrayCallback of Album type. 您可以将Song类型的枚举与Album类型的ArrayCallback一起传递。 (imagine your loadSongs method will be then receiving an ArrayCallback of Album type. No way!) (想象一下,您的loadSongs方法将收到专辑类型的ArrayCallback。没办法!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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