I need implement a command (part of our protocol), after sending the request I am getting 130 parameters as one string divided by special character. I want to implement an efficient way in creating several objects depending on this response. I thought about it and there are two methods I could think of:
- The naive way, just define 130~ variables and assign them to the constructors of the objects.
-
I thought of a way to use reflection, each parameter will be assigned by the definition of the object that I want to create. But there are two main issues with this approach:
- From my experience I know it would take more time than usually assign variables and allocate objects.
- By getting the fields of the object using
data.getClass().getDeclaredFields
the declared files are returned in different order than I am expecting them to be. Is there a way the fields could be returned as declared in the class?
This is the code I done so far:
private Object getExamClassData(Class<?> examClass, String[] examFileFrags, int startIndex, int endDataIndex)
{
ARRefraction data = null;
try
{
Constructor<ARRefraction> ctor = (Constructor<ARRefraction>) ARRefraction.class.getConstructor();
data = ctor.newInstance();
Field[] fields = data.getClass().getDeclaredFields();
int fIndex = 0;
for (fIndex = 0;fIndex<fields.length;fIndex++)
{
try
{
Field field = fields[fIndex];
field.setAccessible(true);
if(field.getType().isAssignableFrom(Float.TYPE))
{
field.set(data, Float.parseFloat(examFileFrags[fIndex+startIndex]));
}
else if(field.getType().isAssignableFrom(Integer.TYPE))
{
field.set(data, Integer.parseInt(examFileFrags[fIndex+startIndex]));
}
else if(field.getType().isAssignableFrom(String.class))
{
field.set(data, examFileFrags[fIndex+startIndex]);
}
}
catch (IllegalArgumentException e1)
{
e1.printStackTrace();
}
catch (IllegalAccessException e1)
{
e1.printStackTrace();
}
}
return data;
}
catch (java.lang.InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
ARRefraction object
public class ARRefraction implements Parcelable
{
private float _sFar;
private float _cFar;
private int _aFar;
private float _pFar;
private float _puFar;
private float _sNear;
private float _cNear;
private int _aNear;
private float _puNear;
private float _pNear;
private String _vaFar;
private float _hoFar;
private float _qFar;
//
private String _vaNear;
private float _hoNear;
private float _qNear;
private float _add;
}
Aucun commentaire:
Enregistrer un commentaire