I'm working on a toString method for reflection. Currently I can handle all primitive types with the following code:
@Override
public String toString() {
StringBuilder result = new StringBuilder();
Field field;
String value;
try {
for (String FIELDS1 : FIELDS) {
field = this.getClass().getDeclaredField(FIELDS1.toLowerCase());
value = field.get(this).toString();
result.append("\n").append(field.getName())
.append("[").append(field.getType().getName()).append("]")
.append(" : ")
.append(value)
.append(",");
}
return result.toString().substring(0, result.length()-1);
} catch (NoSuchFieldException
| SecurityException
| IllegalArgumentException
| IllegalAccessException ex) {
...
}
}
However, as soon as the method encounters an array of primitive types it does not print the entire array, I completely understand why. To solve this I created methods that convert arrays of primitive types to a String and is called via java.lang.reflect.Method
and invoked, but I'm passing an Object and cannot cast the object when passing it can anyone provide me with some insight into solving this problem generically? I want to stay away from libraries for now as I want to gain a better understanding of reflection.
Aucun commentaire:
Enregistrer un commentaire