Kotlin - 如果对象的名称存储在字符串中,则访问类的对象
我有一个类,它有多个伴随对象,它们是字符串列表。 在另一个类(活动)中,我有一个字符串,它可以具有任何伴随对象的名称。有没有一种方法可以在不使用 If/Else 语句的情况下访问其他类的伴生对象。
DataLists
class ProjectDataLists {
companion object {
var Countries: List<String> = listOf(
"USA",
"Canada",
"Australia",
"UK"
)
var Cars: List<String> = listOf(
"Toyota",
"Suzuki",
"Honda",
"Ford"
)
}
}
Activity Class
var IntentVariable: String = "Countries" //This is an Intent variable (extra) from another activity
var DataToBeFetched : List<String>? = null
if (IntentVariable == "Countries")
{
DataToBeFetched = ProjectDataLists.Countries
}
else if (IntentVariable == "Cars")
{
DataToBeFetched = ProjectDataLists.Cars
}
我希望 Activity 类的最后一部分在没有 if/else 的情况下完成
I have a class which is having multiple companion objects which are lists of strings.
In another class (Activity) I am having a string which can have name of any of the companion object. Is there a way of accessing other class's companion object without If/Else statements.
DataLists
class ProjectDataLists {
companion object {
var Countries: List<String> = listOf(
"USA",
"Canada",
"Australia",
"UK"
)
var Cars: List<String> = listOf(
"Toyota",
"Suzuki",
"Honda",
"Ford"
)
}
}
Activity Class
var IntentVariable: String = "Countries" //This is an Intent variable (extra) from another activity
var DataToBeFetched : List<String>? = null
if (IntentVariable == "Countries")
{
DataToBeFetched = ProjectDataLists.Countries
}
else if (IntentVariable == "Cars")
{
DataToBeFetched = ProjectDataLists.Cars
}
I want last part of Activity class to be done without if/else
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用反射:
但是如果您的伴生对象中只有几个列表,我建议不要使用反射。请注意,您可以使用 when 来简化您的 if 语句:
这非常易读,并且与反射相比非常明确和安全。
You could use reflection:
But if you have only a few lists in your companion object, I would recommend to not use reflection. Note that you can simplify your if statement by using when:
This is very readable and in comparison to reflection very explicit and safe.