如何添加Class <! - 类型的参数?扩展broadcastreceiver - >

时间:2017-08-24 09:14:25

标签: java android generics

我必须使用带有此签名的方法

BCR(String id, Class<? extends android.content.BroadcastReceiver> 
receiverClass))

我创建了一个扩展BroadcastReceiver的类,如下所示

public class BCRGeoReference extends BroadcastReceiver {

public BCRGeoReference(Context ctx) {

}

@Override
public void onReceive(Context context, Intent intent) {

}
}

但是当我向方法添加BCRGeoReference时,我收到一条错误说:

required java.lang.class<? extends android.content.BroadcastReceiver>

请告诉我如何将该参数添加到上面发布的方法BCR()

1 个答案:

答案 0 :(得分:0)

你的签名错了。您期望一个类对象具有泛型类型? extends BroadCastReceiver,但事实并非如此。您想传递BroadCastReceiver

的实例

将您的签名更改为此

<T extends BroadcastReceiver> void BCR(String id, T receiverClass)

如果您打算将它用作类对象,那么您必须传递一个类。像

这样的东西
public class TestJava {
    void BCR(String id, Class<? extends BroadcastReceiver> receiverClass){

    }

    public class AnyReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {

        }
    }

    public static void main(String args[]){
        TestJava test = new TestJava();
        test.BCR("s", AnyReceiver.class);
    }
}