I have the following class hierarchy
(POSTRequestHTTP extends ReqeustHTTP)
(RequestHTTP extends ComunicationObjectHTTP )
Assuming that each object can have variables corresponding to an item in a header, and I have to set its values by passing a String and retrieving its values, getting a String at runtime.
In order to not have to implement in all Classes, I have implemented appendices in the class of the highest hierarchical level (CommunicatonObjectHTTP), The following methods:
1st method to search field in the current class and parent classes, by name.
protected Field getHeaderField(String fieldName)
{
Class current = this.getClass();
boolean keepSearch = true;
while(keepSearch)
{
try{
return current.getDeclaredField(fieldName);
}catch(Exception ex){}
if((current = current.getSuperclass())== null)
{
keepSearch = false;
}
}
return null;
}
2nd Method to generate a String containing all field values separated by rows.
public String generateHeaders()
{
String returnValue = "";
for(String name : constList.getConstValues())
{
try{
Field field = this.getHeaderField(this.getFieldNameByHeader(name));
field.setAccessible(true);
Object value = field.get(this);
if(value != null)
{
String stringvalue = ""+value;
if(stringvalue != "")
{
returnValue = returnValue + value + lineSeparator;
}
}
}catch(Exception ex){System.out.println(ex);}
}
if(returnValue != "")
{
returnValue = returnValue.substring(0,returnValue.length()- lineSeparator.length());
}
return returnValue;
}
3rd Get a String set the value of each field per row of a String passed as parameter.
public void loadHeaders(String protocol)
{
if(protocol != null)
{
if(protocol != "")
{
this.headers = protocol;
String[] lines = protocol.split(lineSeparator);
for(String line : lines)
{
if(line == null)
{
break;
}
String[] nameAndValue = line.split(nameAndValueSeparator);
if(nameAndValue.length >= 2)
{
try{
Field field = this.getHeaderField(this.getFieldNameByHeader(nameAndValue[0]));
field.setAccessible(true);
field.set(this,nameAndValue[1]);
}catch(Exception ex){}
}
}
}
}
}
But I tested and even the variable names passed as parameter are correct, an exception occurs saying that these were not found. Could someone please give a hint about some mistake I'm making, or point out a topic talking about it.