2012-08-30 45 views
0

出於好奇。我怎樣才能創建一個新的類,其中構造函數不需要參數?這裏有一個例子:如何從類<?>創建新班級?

public static BroadcastReceiver startBroadcastReceiver(Context context, Class<?> receiverClass, String receiverTag) { 
    BroadcastReceiver receiver = null; 

    IntentFilter intentFilter = new IntentFilter(receiverTag); 

    receiver = new receiverClass(); // <---- What's the correct syntax? 

    if (receiver != null && intentFilter != null) { 
     context.registerReceiver(receiver, intentFilter); 
    } 

    return receiver; 
} 

這是我會怎麼稱呼它:

MyTools.startBroadcastReceiver(context, MyBroadcastReceiver, MyBroadcastReceiver.TAG); 

在此先感謝。

+3

'receiverClass.newInstance();'? – assylias

+1

您想要創建類的* class *或new * object *嗎? – Pshemo

回答

0

使用此:

try{ 
    receiver = (BroadcastReceiver) receiverClass.newInstance(); 
}catch(Exception e){ 
    //do stuff 
} 

你要給它

MyTools.startBroadcastReceiver(context, MyBroadcastReceiver.class, MyBroadcastReceiver.TAG); 
+2

如果將receiverClass的類型更改爲Class <?擴展BroadcastReceiver>。這使得調用類型安全並避免了投射。 –

+0

好的提示。非常感謝。 –

相關問題