【问题标题】:How to Invoke a specific implemented class of a Interface如何调用接口的特定实现类
【发布时间】:2014-01-13 16:01:28
【问题描述】:

我试图完成的是调用特定类的接口。
我使用枚举来填写 .class 并获取该类的接口。
那么如何返回接口呢?
如果可能的话,我想避免反思。

提前致谢。

public interface GameInterface {
    void start();
    void sop();
}

public enum Game{
    MINESWEEPER(MineSweeper.class),
    MARIO(Mario.class);

    private Class c;

    public Game(Class c) {
        this.c = c;
    }

    public GameInterface getGameInterface() {
        // return Interface of the class 
        // So I can call for instance MINESWEEPER.getGameInterface().start()

        // At this momement I use return: 
        // ((GamemodeInterface)this.c.getDeclaredMethod("getInstance", new Class[0]).invoke(null, new Object[0]));
        // *MineSweeper and Mario are Singleton, thats why getInstance
    }
}

澄清: 主要目标是在 MineSweeper 和 Mario 类中访问 Start() 和 Stop() 方法。
用法应该类似于:MINESWEEPER.getGameInterface().start() 但目前我不知道在知道 .class 的情况下获取接口的可靠解决方案。

【问题讨论】:

  • 也许是我,但我不明白你在问什么。如果你没有很快得到一个体面的答案,请试着澄清你的问题。
  • 您需要一个类的实例(即使用new 创建的东西)才能调用非静态方法。
  • 你需要返回任何实现 GameInterface 类型的东西
  • Java没有静态接口,不能通过接口调用静态方法。
  • 为什么不直接使用工厂方法?

标签: java class interface enums


【解决方案1】:

一个更好的主意:

  1. GameInterface 应用到您班级的每个游戏中,并隐含您选择的名称。
  2. 用抽象函数 createGame 声明 enum 并返回您期望的 Game 类的实例,实现这个 createGame 函数到每个 enum 常量:

    class MineSweeper implements GameInterface
    {
        // your code
    }
    
    class Mario implements GameInterface
    {
       // your code
    }
    
     public enum GameType
    {
      MINESWEEPER
      {
         public GameInterface createGame()
         {
          return new MineSweeper();
         }
      },
    
      MARIO
      {
         public GameInterface createGame()
        {
          return new Mario();
         }
      }
    
       public abstract GameInterface createGame();
    }
    

如果您打算使用单例模式,虽然我不能从您的问题中确定,但正如@GaborSch 所建议的那样:您可以在createGame()enum 常量中使用MineSweeper.getInstance() 函数。但是,请尝试在实现 Singleton 时也考虑使用 enum,如 Effective Java book with detail explanation 中所建议的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2011-04-28
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多