簡體   English   中英

實例化抽象超類的子類

[英]Instanciating a subClass of an abstract superClass

我有一個這樣的超類,它有一個工廠方法:

@DiscriminatorColumn(
      name = "etype",
      discriminatorType = DiscriminatorType.STRING
)
public abstract class ChallengeReward {
      public static ChallengeReward createFromFactory(String rewardType){
      ChallengeRewardType type = ChallengeReward.fromString(rewardType);

      ChallengeReward challengeReward = null;
      switch(type){
      case point:
         challengeReward = new PointChallengeReward();
         break;
      case notification:
         challengeReward = new NotificationChallengeReward();
         break;
      case item:
         challengeReward = new ItemChallengeReward();
         break;
      }

      return challengeReward;
   }

   public String getClientId(){
      return "ABCDEF";
   }
}

和子類本身沒有構造函數。 因此,所有挑戰獎勵都與一個名為“ etype”的區分列一起存在於同一表中。

現在的問題是我想以反射方式調用方法getClientId(),但是我無法實例化ChallengeReward,因為它是抽象的。 因此,我需要實例化其子類之一,但不能執行subclass.newInstance()。

我在這里有什么選擇?

編輯1:對不起,我的問題不是很清楚。 問題是我正在編寫將遍歷包中所有類的通用servlet,因此需要進行反射。 盡管該方法實際上是靜態的,但是我不知道如何靜態調用它,因為我只在運行時知道當前類。

編輯2:事實證明您可以調用method.invoke(null)來調用靜態方法,謝謝madth3

我認為您可以通過使用類名本身來獲取該method ,然后按如下所示調用該方法:

     String clientId = null;
     Class challengeRewardClass =Class.forName(ChallengeReward.class.getName());
     Method[] methods = challengeRewardClass.getMethods();
     for(Method method: methods){
        if(method.getName().equals("getClientId")){
            clientId = method.invoke(objectoToBeUsedForMethodCall, null);
        }
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM