簡體   English   中英

在 Java 中,我可以在變量中存儲 class 類型嗎,其中 class 是抽象 ZA2F2ED4F18EBC2B61DZC2 的某個子類?

[英]In Java, can I store a class type in variable, where the class is some subclass of an abstract class?

這個問題是因為這個cf4j 示例代碼而出現的。 特別要注意,它會為每個被評估的推薦實例創建一個新的 QualityMeasure object,如果我們想切換我們的評估方法/使用的 QualityMeasure 子類(當前為RMSE ),我們將不得不搜索並替換每個 QualityMeasure 構造函數.

    // Evaluate PMF Recommender
    plot.addSeries("PMF");
    for (int factors : NUM_FACTORS) {
      Recommender pmf = new PMF(datamodel, factors, NUM_ITERS, RANDOM_SEED);
      pmf.fit();

      QualityMeasure rmse = new RMSE(pmf);  // NEED TO EDIT THIS...
      double rmseScore = rmse.getScore();
      plot.setValue("PMF", factors, rmseScore);
    }

    // Evaluate BNMF Recommender
    plot.addSeries("BNMF");
    for (int factors : NUM_FACTORS) {
      Recommender bnmf = new BNMF(datamodel, factors, NUM_ITERS, 0.2, 10, RANDOM_SEED);
      bnmf.fit();

      QualityMeasure rmse = new RMSE(bnmf);  // AND THIS...
      double rmseScore = rmse.getScore();
      plot.setValue("BNMF", factors, rmseScore);
    }

    // Evaluate BiasedMF Recommender
    plot.addSeries("BiasedMF");
    for (int factors : NUM_FACTORS) {
      Recommender biasedmf = new BiasedMF(datamodel, factors, NUM_ITERS, RANDOM_SEED);
      biasedmf.fit();

      QualityMeasure rmse = new RMSE(biasedmf);  // AND ALSO THIS...
      double rmseScore = rmse.getScore();
      plot.setValue("BiasedMF", factors, rmseScore);
    }

是否可以定義一個(固定)變量來指定我將在整個過程中使用哪種子類?

   private static final QualityMeasureSubclass QM = RMSE;  // Can easily switch to MAE, MSE, etc.

   QualityMeasure qm = new QM(pmf);  // The constructor called depends on the subclass chosen above.
   double qmScore = qm.getScore();
   plot.setValue("PMF", factors, qmScore);

我確實看到我可以排除通用代碼,所以我可以在那個地方調整它,但我不知道上述是否可行。

    private void addQualityMeasureValueToPlot(Recommender rec, LinePlot plot, String plotName, int plotFactor) {
        QualityMeasure qm = new RMSE(rec);  // Only place we need to edit if we want to switch.
        double qmScore = qm.getScore();
        plot.setValue(plotName, plotFactor, qmScore);
    }

    // Evaluate PMF Recommender
    plot.addSeries("PMF");
    for (int factors : NUM_FACTORS) {
      Recommender pmf = new PMF(datamodel, factors, NUM_ITERS, RANDOM_SEED);
      pmf.fit();
      addQualityMeasureValueToPlot(pmf, plot, "PMF", factors);
    }

對於工廠來說,這聽起來像是一份完美的工作。 假設 Java 9,您的構造函數都可以映射到Function<Recommender, QualityMeasure>

Map<Class<?>, Function<Recommender, QualityMeasure>> factories = Map.ofEntries(
        Map.entry(RMSE.class, RMSE::new),
        Map.entry(Other.class, Other::new));

然后簡單地說: factories.get(RMSE.class).apply(rec);

隨意將密鑰從Class<?>更改為字符串或將值更改為帶有附加邏輯的實際 lambda。

暫無
暫無

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

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