I have a class that contains several vectors. Each of these vectors too contain vectors. The fields within these classes contain setters and getters for private strings.
I have one main class in which all the vectors are contained. I instantiate this class, and I need to access the fields that have been set within the vectors.
If the s开发者_运维技巧tructure is like:
public class a{
private Vector a, b, c;
}
private class b{
private Vector d, e, f;
}
All of those classes also have strings with setters and getters-- that is all.
Can I do something like this (assuming this object has vectors whose fields are populated--this is done in a separate part of the code with Digester, but I know this part is correct.)
a myObject = new a;
Vector b = this.b;
for(int i=0;i<b.size();i++){
System.out.println(a.b.get(i).getmyString());
}
if so, how do I now access the methods within each class, b, whose vectors are d e and f?
Please help! :(
First of all, you should create your vectors to be type-specific. Let's assume you're storing objects of the type MyData
into them, so you would have this:
public class MyData {
private String myStringValue;
public String getMyStringValue() {
return this.myStringValue;
}
public void setMyStringValue(String myStringValue) {
this.myStringValue = myStringValue;
}
}
Then you should have your Vectors like this:
private Vector<MyData> a, b, c;
When you have it initialized like this, you can do this to access your objects' values:
// Loop through all MyData objects stored in the Vector b
for(MyData myData : b){
System.out.println(myData.getMyStringValue());
}
As an afterthought, why use a Vector
? You probably don't need Vector's synchronicity, so you would be better off using an ArrayList
.
private List<MyData> b = new ArrayList<MyData>(); // populate the arraylist with objects
Also you would benefit more from studying basic OO stuff about encapsulation (= the getters and setters in my examples). Forget reflection for now and save that to the near future when you have the basics all sorted out.
精彩评论