【问题标题】:Pass Class object to a method将 Class 对象传递给方法
【发布时间】:2014-12-01 03:25:50
【问题描述】:

我正在尝试将Class 传递给一个方法。 Class 在程序运行时会发生变化,因此我想在整个程序中重用相同的方法,而不是在我的resetWords() 方法中调用相同的函数。

这是我卡住的地方:

private void getWords(Class c) {
    singles = c.getSingleSyllables();
    doubles = c.getDoubleSyllables();
    triples = c.getTripleSyllables();
    quadruples = c.getQuadrupleSyllables();
    quintuples = c.getQuintupleSyllables();
}

private void resetWords() {
    if (generated.equals("SOMETHING")) {
        Something c = new Something();
        getWords(c);
    }
    else if (generated.equals("ANOTHER")) {
        Another c = new Another();
        getWords(c);
    }
}

【问题讨论】:

    标签: java class parameter-passing


    【解决方案1】:

    您的要求有点模糊,但也许创建一个 Interface 来定义所有 getXSyllables() 方法。让您的课程(SomethingAnother)实现 Interface。最后,将 getWords 定义为private void getWords(YourInterface c)

    【讨论】:

      【解决方案2】:

      您混淆了类和对象。

      您传递给getWords() 的是一个对象。在第一种情况下,它是Something 类型的对象。在第二种情况下,它是Another 类型的对象。

      此类代码工作的唯一方法是为SomethingAnother(我们称之为HavingSyllabes)定义一个公共基类或接口,包含getWords()中使用的5个方法:getSingleSyllables() , getDoubleSyllabes() 等。getWords() 的签名应该是

      private void getWords(HavingSyllabes c)
      

      【讨论】:

        【解决方案3】:

        如果类总是实现getSingleSyllables()getDoubleSyllables()等。那么你应该考虑从抽象类继承,或者实现一个接口。

        那么……

        private void getWords(YourInterface / YourAbstractClass foo) {
        ...
        }
        

        【讨论】:

          【解决方案4】:

          我认为您正在寻找的是一个界面。你应该像这样声明一个接口:

          public interface Passable
          {
              public List<String> getSingleSyllables();
              public List<String> getDoubleSyllables();
              // ...
          }
          

          然后,让SomethingAnother 实现它们:

          public class Something implements Passable
          {
              // method declarations
          }
          

          现在,将您的方法更改为:

          private void getWords (Passable c) {
              singles = c.getSingleSyllables();
              doubles = c.getDoubleSyllables();
              triples = c.getTripleSyllables();
              quadruples = c.getQuadrupleSyllables();
              quintuples = c.getQuintupleSyllables();
          }
          

          【讨论】:

            【解决方案5】:

            您的问题没有提供足够的细节来清楚地回答。

            根据您的设计/最终目标,您应该了解并了解三个概念:

            • 接口
            • 抽象类
            • 反射

            接口将定义实现该接口的类必须提供的方法。每个实现接口的类都必须提供方法的代码。

            抽象类将提供您正在寻找的行为的单一实现。

            反射是一个高级概念。我建议您此时远离它 - 但您应该注意它。

            鉴于您的示例代码,您可能希望使用抽象类。如果设计得当,您可以通过定义接口、使用抽象类实现该接口然后根据需要扩展该抽象类来提高灵活性/重用性。每个扩展 Abstract 的类都会选择你在 Abstract 类定义中提供的默认实现;该接口将使您在未来轻松扩展。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-01-05
              • 1970-01-01
              • 2023-03-09
              • 2011-09-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多