首页 > 解决方案 > Java:在开关内创建的类的访问对象

问题描述

我有如下场景:

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 ?当类在开关盒内变化时如何获取对象。请尽早帮助我。

标签: javaclassobjectswitch-statementcase

解决方案


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

    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();
    }

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


推荐阅读