title: Hibernate Validator: Intercept Invalid Values
body: <p>I'd like to set up my beans to use both Hibernate Validator (for validation) and Google Guice (for DI and method interception).</p>
  
  <p>Ideally, I'd like to have a setup where any method that "fails" validation will cause a method interceptor to be called:</p>
  
  <pre><code>public class Widget {
      @NotNull
      public Fizz getFizz() {
          return fizz;
      }
  }
  
  public class FailedWidgetInterceptor implements MethodInterceptor {
      public Object invoke(MethodInvocation invocation) throws Throwable {
          // This gets executed if Widget's getFizz() returns null...
      }
  }
  </code></pre>
  
  <p>But it looks like Hibernate Validator only allows you to determine pass/fail status by explicitly passing an object <code>T</code> to a <code>ClassValidator&lt;T&gt;</code>'s <code>getInvalidValues()</code> method.</p>
  
  <p>So I need a place to make such a call!  The <strong>only</strong> viable solution I can think of is to create my own annotation (which I've <em>never</em> done before!) which might look like this:</p>
  
  <pre><code>@NotNull
  public @interface AutoValidatingNotNull {
      // ...??
  }
  </code></pre>
  
  <p>And then in Guice <code>Module</code>:</p>
  
  <pre><code>public class WidgetModule implements Module {
      public void configure(Binder binder) {
          binder.bindInterceptor(
              any(),
              annotatedWith(AutoValidatingNotNull.class),
              new ValidatingWidgetInterceptor()
          );
      }
  }
  
  public class ValidatingWidgetInterceptor implements MethodInterceptor {
      public Object invoke(MethodInvocation invocation) throws Throwable {
          ClassValidator&lt;Widget&gt; widgetValidator = new ClassValidator&lt;Widget&gt;();
  
          InvalidValue[] badVals = widgetValidator.getInvalidValues(widget);
  
          if(badVals.length &gt; 0)
              handleFailedValidationAndThrowRuntimeExceptionOrSomething();
      }
  }
  </code></pre>
  
  <p>Finally, to change <code>getFizz()</code>:</p>
  
  <pre><code>@AutoValidatingNotNull
  public Fizz getFizz() {
      return fizz;
  }
  </code></pre>
  
  <p>For one, this only <em>almost</em> works: inside the interceptor's <code>invoke</code> method, <strong>how do I get my hands on the <code>widget</code> instance (the one we wish to validate)?</strong>. Is there a way to pass the <code>widget</code> instance via annotations?</p>
  
  <p><strong>Edit:</strong><br/>
  Doesn't look like I can pass <code>Object</code> into annotations (as parameters)...</p>
  
  <p>Second, this is kind of nasty. Perhaps I'm overlooking something that Hibernate Validator offers that takes care of all this for me? Is there a better way to go? Thanks in advance!</p>