Note that there are some explanatory texts on larger screens.

plurals
  1. POBlanking fields with Reflection
    text
    copied!<p>I am writing a Junit test framework to test web services.</p> <p>There is a requirement for the input values to come from many different sources, eg an earlier web service call or literals within the class.</p> <p>To achieve this I have constructors that accept the different inputs in different ways; all simple so far.</p> <p>The problem is the webservices also need to be exercised with a full data load and a mandatory fields only payload.</p> <p>Rather then litter the (in some cases verrry long) tests with <code>if</code> statements deciding whether to set a value or not, I have written an annotation @Optional.</p> <p>Adding this annotation causes it to be nulled by the following code:</p> <pre><code> /** * Find all of the fields annotated with optional and null them * @throws IllegalAccessException * @throws IllegalArgumentException */ private void blankOptionalFields() throws IllegalAccessException{ for(Field field: this.getClass().getDeclaredFields()){ Annotation optionalAnnotation = field.getAnnotation(Optional.class); if(!(field.isSynthetic()) &amp;&amp; optionalAnnotation instanceof Optional){ field.setAccessible(true); try{ field.set(this, null); } catch(IllegalArgumentException e){ logger.debug("Tried to set a scalar field to null!", e); } } } } </code></pre> <p>So two things:</p> <p>1: Although this works it somehow feels fragile/dangerous, there must be a better approach? 2: If this is not a carzy approach, what is the best way to go about setting the scalar values to appropiate values?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload