Initialize all String members with an empty string

I want all members of a String object to be on an empty string if they are null.

pseudo code:

foreach member in object { if (member instanceof String and member == null) { member = ''; } } 

What is the easiest way to achieve this? Any infrastructure / tool I can use? Write your own solution through reflection?

+6
source share
5 answers
 public static void setEmpty(Object object) throws IllegalArgumentException, IllegalAccessException { Class<?> clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (String.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, ""); } } } } 
+5
source

You can use reflection to display all the fields of an object, and then check and modify it. You may need to change the access level if they are private. You can find many guides on this subject when searching on Google, for example. this one .

+1
source

Try using AspectJ:

 @Aspect public class StringHandler { @Around("execution(String com....YourClass.*(*))") public Object handle(ProceedingJoinPoint thisJoinPoint) throws Throwable { String s = (String) thisJoinPoint.proceed(); if (s == null){ return ""; } return s; } } 

This will be faster at runtime since this aspect will be compiled into bytecode, otherwise reflection will be used at runtime and will slow down your application.

+1
source

Another way is to write a utility that generates code that sets empty lines for members of certain objects.

0
source

In favor of a reusable design, you should consider using a default value for null values, like the Apache common defaultString API, something like this:

 public String getValue(String value){ return StringUtils.defaultString(value); } 

You can also use defaultString(String str,String defaultStr) so that you have the ability to change the default value to something if there is any reason for this.

StringUtils documentation

0
source

Source: https://habr.com/ru/post/902524/


All Articles