2

私はこのようなスーパークラスを持っています、それはファクトリメソッドを持っています:

@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をインスタンス化できません。そのため、そのサブクラスの1つをインスタンス化する必要がありますが、subclass.newInstance()を実行できません。

ここでの私のオプションは何ですか?

編集1:申し訳ありませんが、私の質問はあまり明確ではありませんでした。問題は、パッケージ内のすべてのクラスを通過する汎用サーブレットを作成しているため、リフレクションが必要なことです。そのメソッドは実際には静的ですが、実行時に現在のクラスしか知らないため、静的に呼び出す方法がわかりません。

編集2:静的メソッドを呼び出すためにmethod.invoke(null)を呼び出すことができることがわかりました、ありがとうmadth3

4

1 に答える 1

1

I think you can get the method through using the class name itself and then invoke the method as below:

     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);
        }
     }
于 2012-10-24T18:56:58.337 に答える