[英]How to iterate through nested classes?
Another simple one! 另一个简单的!
I'm trying to iterate through nested classes in an android project. 我正在尝试遍历android项目中的嵌套类。
The class structure is: 类结构为:
public class clsMessage {
public String Username = "";
public String Password = "";
public String Request = "";
public class Parameters {
public String Name = "";
public String Value = "";
}
}
The outer class is instantiated as "msg". 外部类被实例化为“ msg”。 Then I thought I'd query it like this:
然后我想我会像这样查询它:
for (clsMessage.Parameters params : msg) {
// do stuff
}
But that doesn't work and I can't find an example on Google surprisingly, unless I should be using an iterator in the outer class? 但这是行不通的,除非我应该在外部类中使用迭代器,否则我无法在Google上找到一个示例。
I am guessing you are looking for something like the following. 我猜您正在寻找类似以下的内容。
public class ClsMessage
{
public String username = "";
public String password = "";
public String request = "";
public List<Parameters> parameters = new ArrayList<Parameters>();
public static class Parameters {
public String name = "";
public String value = "";
}
}
for(ClsMessage.Parameters param : clsMessage.parameters)
{
....
}
Just declaring an inner class won't actually have an "inner class" as a field. 仅声明一个内部类实际上并没有一个“内部类”作为字段。 You would need to make a field for it.
您需要为此创建一个字段。 Considering you wanted to iterate through it with a for-loop, I assumed you wanted more than one
Parameters
in your message, so I added a List
. 考虑到您想使用for循环进行遍历,我假设您在消息中需要多个
Parameters
,因此添加了一个List
。
Iterate over list of messages and then get inner class object each ClsMessage
. 遍历消息列表 ,然后获取每个
ClsMessage
内部类对象。
for (clsMessage msg : msgs) {
clsMessage.Parameters params = msg.getParameter();
//do stuff like params.getName()...
}
If your outer class should hold a list of inner class instances, it should have some array or Collection of Parameters. 如果您的外部类应包含内部类实例的列表,则它应具有一些数组或参数集合。
public class clsMessage {
....
private Parameters[] params; // or private List<Parameters> params;
public Parameters[] getParams() // or public List<Parameters> getParams()
{
return params;
}
public class Parameters {
public String Name = "";
public String Value = "";
}
}
Then you can access them : 然后,您可以访问它们:
for (clsMessage.Parameters params : msg.getParams()) {
// do stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.