我有一个包含
字段的课程ArrayList<Double> a = new ArrayList<Double>();
在我的fileReader类中,我从文件中读取数据,并将上述类的字段设置为从文件中读取的值。
public void getInfo( String tag, Object obj )
{
//code
Field b = obj.getClass().getDeclaredField( "name" );
//I can change the values of the fields, if they are int, string, double...etc
// with b.setDouble(Object obj, double d) method or the corresponding methods
}
如何向ArrayLists添加数据?
编辑:我是初学者,所以如果您认为有更好的方法来解决这个问题,请告诉我。如果我不清楚,我会说如果Field b是一个ArrayList,我将如何向其中添加数据。我这样编写这个类,所以我可以从文件中获取任何数据类型,并将其设置为我可能需要的某个类中的字段。
edit2:在我的数据文件中,我向数据添加了标签,告诉我数据的名称和类型。而且我不会只使用obj.a.add(123.45),因为我不知道我想改变的字段是a,而a是一个arraylist。
解决:感谢您的所有帮助!遵循A4L的建议,代码应为
if ( b.get( obj ) instanceof ArrayList )
{
ArrayList<Double> temp = (ArrayList<Double>)b.get( obj );
temp.add( /*your data*/ );
}