java - 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 ?当类在开关盒内变化时如何获取对象。请尽早帮助我。
解决方案
也许您也可以执行以下操作:
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();
}
但请注意,如果没有满足任何开关情况,它将仍然为空。
推荐阅读
- javascript - 如何将数组从php传递给ajax成功函数?
- c# - 如何在顶部导航栏上显示标题名称而不是 xamarin 表单外壳中的汉堡图标
- spring - Spring Feign 不压缩响应
- sql-server - Why is flume not writing data to S3 in Mumbai region?
- reactjs - React particles not interacting on hover after adding an image in background?
- python - 以迭代和交互方式编写和测试 python 代码
- python - 如何将模块预加载到 python 脚本中?
- zoho - 在 Zoho Creator 中,无法将决策从 Zoho Workflow(deluge 脚本)传递到 Zoho Form
- content-management-system - 如何在 Opencart 上进行分期付款
- php - 二叉遍历树从左到右 MYSQL PHP