【问题标题】:How to pass a parameter to a class between different modules' same classes in java?java - 如何在java中不同模块的相同类之间将参数传递给类?
【发布时间】:2016-12-01 11:58:06
【问题描述】:

我有 5 个模块,所有模块都包含相同的类,但所有类的内容在 run 方法中都有不同的代码。

mainpackage
    |  \ moduleA
    |       \ LoginClass
    |            + run(hashMapContext)
    |       \ LogOutClass
    |             + run(hashMapContext)
    |       \ GetInfoClass
    |             + run(hashMapContext)
    |
    |  \ moduleB
    |       \ LoginClass
    |             + run(hashMapContext)
    |       \ LogOutClass
    |             + run(hashMapContext)
    |       \ GetInfoClass
    |             + run(hashMapContext)

我有一个字段(moduleType),我正在尝试这个

moduleType = moduleA

getInfo.run(hashMapContext)

如何开发此代码? enter image description here

感谢@Jhon D,这是答案。

public static void main(String[] args) {

        ICommon obj = newInstance("a");
        obj.run("expect A");

    }


    public static ICommon newInstance(String type) {

        switch (type) {
            case "a":
                return new ModuleALogin();
            case "b":
                return new ModuleBLogin();
            default:
                return null;
        }

    }

【问题讨论】:

  • 你应该使用抽象类...
  • 我认为,你应该从重新设计开始,你应该创建一个包含模块中常见的所有类的 jar。将其包含在 Modules 的类路径中
  • getInfo.run() 这个方法从何而来?而且我没有看到moduleType = moduleAgetInfo.run(hashMapContext) 之间的关系此外,模块是什么意思?
  • 模块A和B的不同包中是否有LoginClass ..对(这是基本的..)? .
  • 什么都没有,我只是在计划和思考我该怎么做。 @davidxxx

标签: java inheritance interface abstract-class


【解决方案1】:

使用包含方法的通用接口:run(hashMapContext)

好的,如果你想举例。它可能类似于:

public void foo() {
    // ...
    CommonInterface obj = newInstance(module);
    obj.run(hashMapContext);
    // ...
}

public CommonInterface newInstance(module) {
    switch (module) {
        case A:
            return ClassFromModuleA;
        case B:
            return ClassFromModuleB;
        // ...
    }
}

【讨论】:

  • 我想过,但我怎样才能将参数传递给正确的模块?有代码示例吗?
猜你喜欢
  • 2013-01-30
  • 2012-10-27
  • 2022-06-26
  • 2012-01-07
  • 2014-05-25
  • 2021-07-10
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多