2017-05-14 169 views
1

我有幾個類(例如,領域表)。 我以相同的方式處理每個對象(請參閱下面的代碼)。類處理,重複代碼

僅更改班級的名稱:Ticket.class,進一步它將是SecondTable.class依此類推。 類名是事先知道的。

Q1。如何使一個類作爲參數的方法?

Q2。或者我怎麼能做一些像「每個[classes] do ...」?

Realm realm = Realm.getDefaultInstance(); 
RealmResults<Ticket> tickets = realm.where(Ticket.class).findAll(); 
realm.beginTransaction(); 
for (int i = tickets.size() - 1; i >= 0; i--) { 
    if ... { 
     Notification notification = new NotificationCompat.Builder(this)...; 
     StartMyAsyncTask().execute(tickets.get(i)); 
     // etc... 

     // delete from DB 
     tickets.get(i).removeFromRealm(); 
    } 
} 
realm.commitTransaction(); 

而且Ticket類的樣子:

public class Ticket extends RealmObject {... } 
+0

打開** **前查詢 – EpicPandaForce

回答

2

你可以創建一個聯合接口:

public interface IAction { 
    void action(); 
} 

TicketSecondTable並實現這一點:

public class Ticket extends RealmObject implements IAction { 

    @Override 
    public void action(){...} 
} 

的下一步是模板方法(可能在你的Utils類):

public static <T extends RealmObject & IAction> void yorForEachMethod(Class<T> cls) { 
    Realm realm = Realm.getDefaultInstance(); 
    RealmResults realmObjects = realm.where(cls).findAll(); 
    realm.beginTransaction(); 
    for (int i = realmObjects.size() - 1; i >= 0; i--) { 
     if ... { 
      Notification notification = new NotificationCompat.Builder(this)...; 
      // you can evaluate implementation of action method from IAction interface 
      ((IAction)realmObjects.get(i)).action(); 
      // or pass to assync task and work with IAction interface 
      //StartMyAsyncTask().execute((IAction)realmObjects.get(i)); 
      // etc... 

      // delete from DB 
      realmObjects.get(i).removeFromRealm(); 
     } 
    } 
    realm.commitTransaction(); 
} 
+1

非常感謝!有效。 – tim4dev

+0

@ tim4dev,歡迎您! )如果答案已回答您的問題,您應該將答案標記爲已接受。 https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Sergey

0

1.You可以創建一個類的方法爲Object:你會被更新的每個對象

public void yourMethod(Object yourclass) {} 

2.Since和每一次。創建一個新的實例,並調用上述生成的方法:

yourMethodClass.yourMethod(ObjectName); 
+0

對不起,我寫的是一個過於簡單化的示例代碼交易。我做了更正。 – tim4dev