【问题标题】:Java: Access Object of a class created inside switchJava:在开关内创建的类的访问对象
【发布时间】:2019-03-19 19:11:49
【问题描述】:

我有如下场景:

String artifactName="testplan"; //or at times "testsuite" can come
switch (artifactName) {
            case testplan: {
                TestPlan artifact = new TestPlan();
            }
            case testsuite: {
                TestSuite artifact = new TestSuite();   
            }

从上面我希望得到开关之外的工件对象。 在两个类(TestSuite 和 TestPlan)中,我都有一个属性,当我获得工件并相应地使用对象时,我将设置它。准确地说,我将使用它将此对象转换为 xml(xml 因类而异)。如何让工件脱离 switch ?当类在开关盒内变化时如何获取对象。 请尽早帮助我。

【问题讨论】:

  • 您可以在交换机之外将artifact 声明为Object artifact
  • 是的。明白了!!!

标签: java class object switch-statement case


【解决方案1】:

也许您也可以执行以下操作:

    String artifactName="testplan"; 
    Object artifact;//create reference 


    switch (artifactName) {
                case testplan: {
                    artifact = new TestPlan();//assing it here
                    break;
                }
                case testsuite: {
                    artifact = new TestSuite();//or here 
                    break;
                }

因此,您需要直接处理您的一个类的实例。你知道。我完全是 Java 新手。如果有人会为此提供更好的想法,那就太好了。但现在我看到了唯一的解决方案。

  if(object instanceof TestPlan){
        ((TestPlan) object).doMethod();
    }else if (object instanceof TestSuite){
        ((TestSuite)object).doMethod();
    }

但请注意,如果没有满足任何开关情况,它仍然为空。

【讨论】:

  • 感谢您的回复。但是切换执行后,我会有 artifact.setCustomAttribute("sdfsdf")。此 setCustomAttribute 方法适用于测试计划和测试套件类/对象。当我尝试上述建议的方式时,我收到类似“对象类型的方法 setCustomAttribute(RQMCustomAttributes) 未定义”的消息。请帮助我。
  • 我已经为你编辑了我的答案
【解决方案2】:

在 switch 块之外创建 TestPlan 类型的引用“工件”(TestSuite 扩展 TestPlan),然后在 case 语句内分配对象(TestPlan/TestSuite) 根据您所需的条件。下面的代码工作正常。

如果您想使用在两个类中都可用的通用方法,并使用继承和多态的概念。您可以在 TestSuite(child) 中扩展 TestPlan(Parent) 并且可以使用 TestPlan 引用而不是对象引用。

 String artifactName="testplan"; 
        TestPlan artifact;// Test Plan is the Parent class and extend it to TestSuite
        switch (artifactName) {
                    case "testvplan": {
                        artifact = new TestPlan();
                        break;
                    }
                    case "testsuite": {
                        artifact = new TestSuite();   
                        break;
                    }
                    default : {
                        //some code for default condition
                    }

}

【讨论】:

  • 感谢您的回复。但是切换执行后,我会有 artifact.setCustomAttribute("sdfsdf")。此 setCustomAttribute 方法适用于测试计划和测试套件类/对象。当我尝试上述建议的方式时,我收到类似“对象类型的方法 setCustomAttribute(RQMCustomAttributes) 未定义”的消息。请帮助我。
  • 这是因为 setCustomAttribute(String) 未在对象类中定义,您正在调用对象类引用上的方法。
猜你喜欢
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 2020-09-20
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多