Reputation: 1458
Hi I want to convert a class's all String
field values to their uppercase format. How can I do this? Please help.
Example:
public class ConvertStringToUppercase{
private String field1; //to be converted Uppercase
private String field2; //to be converted Uppercase
private String field3; //to be converted Uppercase
...... //more fields
}
Upvotes: 1
Views: 9490
Reputation: 4945
try {
ConvertStringToUppercase testClass = new ConvertStringToUppercase();
for (Field field : testClass.getClass().getDeclaredFields()) {
if (field.getType().equals(String.class)) {
if (!field.isAccessible())
field.setAccessible(true);
if (field.get(testClass) != null && ((String) field.get(testClass)).trim() != "") {
field.set(testClass, ((String) field.get(testClass)).toUpperCase());
}
}
}
} catch (Exception e) {e.printStackTrace();}
Upvotes: 3
Reputation: 691973
public class ConvertStringToUppercase{
private String field1; //to be converted Uppercase
private String field2; //to be converted Uppercase
private String field3; //to be converted Uppercase
public void toUpperCase() {
this.field1 = this.field1.toUpperCase();
this.field2 = this.field2.toUpperCase();
this.field3 = this.field3.toUpperCase();
// ...
}
}
Or, if you want immutability:
public class ConvertStringToUppercase{
private String field1; //to be converted Uppercase
private String field2; //to be converted Uppercase
private String field3; //to be converted Uppercase
public ConvertStringToUppercase toUpperCase() {
return new ConvertStringToUppercase(this.field1.toUpperCase(),
this.field2.toUpperCase(),
this.field3.toUpperCase(),
// ...);
}
}
Make sure to check for null if the fields are nullable.
Upvotes: 5
Reputation: 62459
You can use reflection for a quick and dirty solution:
ConvertStringToUpperCase t = new ConvertStringToUpperCase();
for(Field f: t.getClass().getDeclaredFields()) {
if(f.getType().equals(String.class)) {
f.setAccessible(true);
f.set(t, ((String)f.get(t)).toUpperCase());
}
}
This is not a nice approach however, since private fields should not be modified this way.
Upvotes: 2
Reputation: 2812
You can do it using reflection but it will be ugly and slow.
Use ConvertStringToUppercase.class.getDeclaredFields()
to get Field
objects. Then use field.getType() == String.class
to determine when field is of String type.
Then use field.get(this)
to get the string, uppercase it, then use field.set(this, upperCaseString)
to set the field to the new value.
Upvotes: 2