'OpenCVS: How to get an objects all field values as array? [closed]
I have 3 domain classes like below and I need their values as a string array like in the example.
It is very time consuming and error prone to write all fields one by one like this, maybe there is a quicker way? It will iterate over all fields and get their string values
Maybe with guava or reflection?
Class Cart1{
//Domain class with 100s of fields with getters & setters
public String[] toStringArray() {
return new String[]{
nullToEmpty(String.valueOf(getSomeItem1())),
nullToEmpty(String.valueOf(getOtherItem2())),
.
nullToEmpty(String.valueOf(getSomeFreakItem100())),
}
}
Edit : I need this for opencvs, it expects for a String[] as in this example:
Solution 1:[1]
Field[] fields = Cart1.getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i= 0; i < fields.length; i++) {
fieldNames[i] = fields[i].getName();
}
Solution 2:[2]
You can use Introspector for programmatically read values from POJOs
public String[] toStringArray() {
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(getClass()).getPropertyDescriptors();
List<String> values = new ArrayList<String>();
for (PropertyDescriptor descriptor : propertyDescriptors) {
Method readMethod = descriptor.getReadMethod();
if (!readMethod.getName().equals("getClass")) {
values.add(nullToEmpty((String) readMethod.invoke(this)));
}
}
return values.toArray(new String[0]);
}
Solution 3:[3]
With Java reflection you could use something like below. Get all getter methods (except getClass()) from your class, then invoke them on an instance of this class and pack into an array.
Or, you can think of using other data structure for your data. E.g. Map, with item name as a map key and item value as a map value.
public String[] toStringArray(Cart cart) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
List<Method> getters = getGetters(cart.getClass());
String[] result = new String[getters.size()];
for (int i = 0; i < getters.size(); i++) {
Object value = getters.get(i).invoke(cart);
result[i] = String.valueOf(value);
}
return result;
}
private List<Method> getGetters(Class clazz) throws SecurityException {
List<Method> getters = new ArrayList<Method>();
for (Method method : clazz.getMethods()) {
if (method.getName().startsWith("get") && !"getClass".equals(method.getName())) {
getters.add(method);
}
}
return getters;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jpdymond |
| Solution 2 | renke |
| Solution 3 | Jakub Godoniuk |
