I have an API which I am turning into an internal DSL. As such, most methods in my PoJos return a reference to this so that I can chain methods together declaratively as such (syntactic sugar).
myComponent
.setID("MyId")
.setProperty("One")
.setProperty2("Two")
.setAssociation(anotherComponent)
.execute();
My API does not depend on Spring but I wish to make it 'Spring-Friendly' by being PoJo friendly with zero argument constructors, getters and setters. The problem is that Spring seems to not detect my setter methods when I have a non-void return type.
The return type of this is very convenient when chaining together my commands so I don't want to destroy my programmatic API just be to compatible with Spring injection.
Is there a setting in Spring to allow me to use non-void setters?
Chris
Thanks to all (and especially Espen who went to a lot of effort to show me the various options within Spring).
In the end, I found a solution myself that doesn't require Spring configuration.
I followed the link from Stephen C then found a reference to the SimpleBeanInfo class within that set of Threads. This class allows a user to write their own bean method resolution code by placing another class in the same package as the class with the non-standard setters/getters to override the logic of with 'BeanInfo' appended onto the classname and implementing the 'BeanInfo' interface.
I then did a search on Google and found this blog which pointed the way. The solution on the blog was quite basic so I padded it out for my purposes.
Per Class (with fluent setters)
public class MyComponentBeanInfo<T> extends SimpleBeanInfo {
private final static Class<?> _clazz = MyComponent.class;
PropertyDescriptor[] _properties = null;
public synchronized PropertyDescriptor[] getPropertyDescriptors() {
if (_properties == null) {
_properties = Helpers.getPropertyDescriptionsIncludingFluentSetters(_clazz);
}
return _properties;
}
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(_clazz);
}
}
PropertyDescriptor generation method
public static PropertyDescriptor[] getPropertyDescriptionsIncludingFluentSetters( Class<?> clazz) {
Map<String,Method> getterMethodMap = new HashMap<String,Method>();
Map<String,Method> setterMethodMap = new HashMap<String,Method>();
Set<String> allProperties = new HashSet<String>();
PropertyDescriptor[] properties = null;
try {
Method[] methods = clazz.getMethods();
for (Method m : methods) {
String name = m.getName();
boolean isSetter = m.getParameterTypes().length == 1 && name.length() > 3 && name.substring(0,3).equals("set") && name.charAt(3) >= 'A' && name.charAt(3) <= 'Z';
boolean isGetter = (!isSetter) && m.getParameterTypes().length == 0 && name.length() > 3 && name.substring(0,3).equals("get") && name.charAt(3) >= 'A' && name.charAt(3) <= 'Z';
if (isSetter || isGetter) {
name = name.substring(3);
name = name.length() > 1
? name.substring(0,1).toLowerCase() + name.substring(1)
: name.toLowerCase();
if (isSetter) {
setterMethodMap.put(name, m);
} else {
getterMethodMap.put(name, m);
}
allProperties.add(name);
}
}
properties = new PropertyDescriptor[allProperties.size()];
Iterator<String> iterator = allProperties.iterator();
for (int i=0; i < allProperties.size(); i++) {
String propertyName = iterator.next();
Method readMethod = getterMethodMap.get(propertyName);
Method writeMethod = setterMethodMap.get(propertyName);
properties[i] = new PropertyDescriptor(propertyName, readMethod, writeMethod);
}
} catch (IntrospectionException e) {
throw new RuntimeException(e.toString(), e);
}
return properties;
}
Advantages to this approach:
No custom spring configuration (Spring is not aware of the non-standard setters and sees them as normal). No dependancy on any Spring .jar files but accessible from Spring.
Just seems to work.
Disadvantages to this approach:
I have to place create a BeanInfo class for all of my API classes with non-standard setters. Luckily there are only around 10 such classes and by moving the method resolution logic into a seperate class I only have one place to maintain.
Closing Thoughts
In my opinion, Spring should deal with fluent setters natively, they don't hurt anyone and it should just ignore the return value.
By requiring that setters be rigidly void, it has forced me to write a lot more boiler plate code than I would have needed otherwise. I appreciate the Bean Specification, but bean resolution is trivial using reflection without even using the standard bean resolver so Spring should offer the option of its own bean resolver that will handle this situations.
By all means, leave the standard mechanism as the default, but offer a one-line configuration option. I look forward to future versions where this might be optionally relaxed.
Is there a setting in Spring to allow me to use non-void setters?
The simple answer is No - there is no such setting.
Spring is designed to be compatible with the JavaBeans spec, and that requires the setters to return void.
For a discussion, refer to this Spring Forums thread. There are possible ways around this limitation mentioned in the forum, but there is no simple solution, and I don't think anyone actually reported that they had tried this and that it worked.
Spring can also be configured with Java configuration.
An example:
#Configuration
public class Config {
#Bean
public MyComponent myComponent() {
return MyComponent
.setID(id)
.setProperty("One", "1")
.setProperty("Two", "2")
.setAssociation(anotherConfig.anotherComponent())
.execute();
}
#Autowired
private AnotherConfig anotherConfig;
#Value("${id}")
private String id;
}
You have a nice immutable object. You have actually implemented the Builder pattern!
Updated to respond to Chris's comment:
I guess it's not exactly what you want, but using properties files solves some issues. See the id field in the example above.
Else, you can use Spring's FactoryBean pattern:
public class MyComponentFactory implements FactoryBean<MyComponent> {
private MyComponent myComponent;
public MyComponentFactory(String id, Property propertyOne, ..) {
myComponent = MyComponent
.setID(id)
.setProperty("One", "1")
.set(..)
.execute();
}
public MyComponent getObject() throws Exception {
return myComponent;
}
public Class<MyComponent> getObjectType() {
return MyComponent.class;
}
public boolean isSingleton() {
return false;
}
}
With the FactoryBean, you shield the configuration from the object returned from the getObject() method.
In the XML configuration, you configure the FactoryBean implementation. In this case with <constructor-arg /> elements.
One simple suggestion, it is customary not to use setters, but the properties names themselves. So have a setter, and have another method for the builder:
component.id("MyId")
.property("One")
.property2("Two")
.association(anotherComponent)
.execute();
As far as I know, there is no simple switch. Spring uses the Beans convention, and expects a void setter. Spring works with beans at the property level via an instance of the BeanWrapper interface. The default implementation, BeanWrapperImpl, uses introspection, but you could create your own modified version that uses reflection to find methods matching your pattern.
EDIT: Looking at the Spring code, BeanWrapperImpl is hard-wired into the bean factories, there is no simple way to replace this with another implementation. However, as spring uses introspection, we can work on getting java.beans.Introspector to produce the results we want. Here are the alternatives in order of decreasing pain:
change the method signature on your setters to comply.
implement your own BeanInfo classes for each of your beans
Use reflection to plug dynamically generated BeanInfo classes into the introspector.
The first two options are probably not really options for you, as they involve quite a lot of changes. Exploring the third option in more detail:
To know which beans are being instantiated by spring, implement your own BeanFactoryPostProcessor. This gets to see all the bean definitions before they are used by the BeanFactory. Your implementation iterates over all the BeanDefinitions in the factor, and fetches the bean class from each definition. Now you know all the classes that are being used.
With a list of classes, you can set about creating your own BeanInfos for these classes. You use the Introspector to generate the default BeanInfo for each class, which would give you read-only properties for your properties with return value setters. You then create a new BeanInfo, based on the original, but with PropertyDescriptors referencing setter methods - your return value setters.
With new beanInfos generated for each class, you need to make sure that the Introspector returns these when asked for the beaninfo for your class. The introspector has a private Map that is used to cache beanInfos. You can get hold of this via reflection, enable access - setAccessible(true) - and add your BeanInfo instances to it - map.put(Class,BeanInfo).
When spring asks the Introspector for the BeanInfo for your bean class, the introspector returns your modified beanInfo, complete with setter methods mapped to your setters with return values.
As others have said, it's not just Spring-friendliness you risk losing. A non-void setter isn't really a setter as far as JavaBeans are concerned, and all sorts of other tools (validators, marshallers, viewers, persisters, whatever else you can dream up) will probably use Introspector and BeanInfo, which expect setters to be null.
With this in mind, how flexible is the requirement that they be called setX? A lot of fluent interfaces in Java use withX instead. If you're using Eclipse, you can probably create a code generation template to make X getX(), void setX(X x), and X withX(X x) for you. If you're using some other codegen tool, I can imagine adding withX fluent setter/getter methods would also be easy.
The with word seems a bit odd, but when you see it alongside a constructor it reads really well.
Request r = new Request().withEndpoint("example.com")
.withPort(80)
.withSSL(false)
.withFoo("My Foo");
service.send(r);
One such API is the AWS SDK for Java, which you can consult for examples. An off-topic caveat is that boolean getters may be called isX, but Boolean getters must be called getX.
Related
Assume I have a configuration class accessible via the stock CDI that defines some application-wide parameters:
#ApplicationScoped
class AppConfig {
public double getMaxAllowedBrightness() { ... }
};
And I have a simple class for my data objects:
class LightSource {
double brightness;
...
boolean isValid() {
double maxAllowedBrightness = ...; // Somehow use AppConfig#getMaxAllowedBrightness() here
return brightness <= maxAllowedBrightness;
}
}
How can my data object access the single AppConfig instance?
Somehow I hate the idea of autowiring AppConfig into every single data object (there are lots of them). Is there any other way to get access to AppConfig in the above example from my data object?
What's the best pattern to use here?
The simplest example is a runtime lookup akin to:
import jakarta.enterprise.inject.spi.CDI;
CDI.current().select(cls).get();
With cls being the class that you're looking up. (Note the package name, this is the latest version of CDI 2.x in the new jakarta namespace, the original is in javax.)
It gets more detailed from there, but that's the gist of it.
Note, that semantically there's little difference between autowiring something and doing a runtime lookup, especially for something mostly static at the instance level. It's still a dependency. You still have to touch the code of the classes to pull it off.
A nice thing of relying on the autowiring is that you can disable it situationally, and the class reverts to a simple bean, that you can do with what you will. Coding in the lookup, it's a little bit more than that.
Dynamic lookup is more for special circumstances.
On my current project, our team has been doing this using the #Value annotation. In our case, we have all the properties in a properties bean, which I'll call mainAppConfiguration. The bean is populated from a properties file like main-app-config.properties (which was read into the bean with a Properties prop = new Properties().load(mainAppConfigFilePath) method.
Assuming you have something like that set up, then we inject the properties into the classes that need them using a little SpEL magic something like:
private Integer refreshRateSeconds;
#Value("#{ mainAppConfiguration.getProperties()['funny-property-base-name.refreshRateSeconds'] }")
public void setRefreshRateSeconds(Integer refreshRateSeconds) {
if (refreshRateSeconds == null) {
throw new IllegalArgumentException("Required config property 'funny-property-base-name.refreshRateSeconds' was not found"));
}
this.refreshRateSeconds = refreshRateSeconds;
}
Baeldung has examples (without defaults) and more with defaults.
I've been hacking with Google Guice a bit lately and I came up with an idea to inject a String to a constructor according to the class it is being declared in and other several parameters defined in an annotation. For example:
If I define a new qualifier annotation #NamedInjectable to be used by Guice:
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.FIELD, ElementType.PARAMETER })
#Qualifier
public #interface NamedInjectable
{
String name() default "";
boolean indexed() default true;
}
Where name is a new name base for the string (default is only the class' name), and indexed states whether or not the name should be incremented each time a new string is being injected.
e.g.
public MyClass {
#Inject
public MyClass(#NamedInjectable(name = "foo", indexed = true) String name) {
// some code
}
}
And name param should be given a value such as "
I considered using Provider Bindings or AssistedInject but I could get it done. One main reason to failing, is somehow getting the name of the class.
Do you have any other idea?
There's no built-in way to customize a standard Guice binding based on names. If you want to stick to Guice alone, you'll probably need Custom Injections.
In addition to the standard #Inject-driven injections, Guice includes hooks for custom injections. This enables Guice to host other frameworks that have their own injection semantics or annotations. Most developers won't use custom injections directly; but they may see their use in extensions and third-party libraries. Each custom injection requires a type listener, an injection listener, and registration of each.
Guice's documentation example for Custom Injections demonstrates a logger instance customized with the type of the injecting class, which sounds very much like something you want to do—it's no more difficult to read the parameters of the annotation you create from within your TypeListener. However, this doesn't work directly with #Inject annotations or constructors, so you may have trouble if you're trying to make the injection happen entirely behind the scenes.
Another option is much simpler: Just use a factory and pass in the newly-constructed class.
public MyClass {
private final String name;
#Inject
public MyClass(NameInjector nameInjector) {
this.name = nameInjector.get(this, "foo", true);
}
}
For ordinary Guice injections, you can't access the name of the class where the something is being injected. If you really need to do that, you would need to use custom injection.
By using a custom TypeListener, you can listen for injection events and know the class that is being injected. On hearing an injection event, you can register a custom MembersInjector that Guice will invoke after it finishes its own injections. This MembersInjector has access to the fully-constructed instance of the class, so it can reflect on fields and inspect annotations. However, it obviously can't inject constructor parameters, since the object has already been created.
In short, there is no way to do custom injection of constructor parameters. But the idea you describe is very possible for field injection!
How to do it
First, you need to register a TypeListener (this code based on the linked Guice wiki page):
public class NamedStringListener implements TypeListener {
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
Class<?> clazz = typeLiteral.getRawType();
while (clazz != null) {
for (Field field : clazz.getDeclaredFields()) {
if (field.getType() == String.class &&
field.isAnnotationPresent(NamedInjectable.class)) {
Annotation annotation = field.getAnnotation(NamedInjectable.class);
// How you create and configure this provider is up to you.
Provider<String> provider = new MyStringProvider(clazz, annotation);
typeEncounter.register(new MyMembersInjector<T>(field, provider));
}
}
clazz = clazz.getSuperclass();
}
}
}
Then, inside MyMembersInjector<T>:
public class MyMembersInjector<T> implements MembersInjector<T> {
final Field field;
final Provider<String> provider;
NamedMembersInjector(Provider<String> provider) {
this.field = field;
this.provider = provider;
this.field.setAccessible(true);
}
public void injectMembers(T t) {
field.set(t, provider.get());
}
}
I leave the implementation of MyStringProvider up to you.
See the Guice CustomInjections wiki page for more.
I am trying to access the values of some fields from the backing bean of a JSF page via reflection. The problem is that when I use the getter I get the correct value but when I use the get(obj) method of the necessary fields I always get a null value returned.
Getting the beanObject:
ELContext elcontext = FacesContext.getCurrentInstance().getELContext();
Object beanObject = FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elcontext, null, beanName);
To get the fields values without using the getter I do the following:
List<Field> fields = new ArrayList<Field>();
ParamsBuilder.getAllFields(fields, beanClass);
for(Field field: fields) {
field.setAccessible(true);
System.out.println(field.getName() + ": " + field.get(beanObject)); //just to see if it works
}
The getAllFields method has this implementation:
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
for (Field field: type.getDeclaredFields()) {
fields.add(field);
}
if (type.getSuperclass() != null) {
fields = getAllFields(fields, type.getSuperclass());
}
return fields;
}
To get the values by using the getter I do the following:
private ClassX getValue(Object beanObject, Class<?> beanClass) throws Exception {
Method getter = beanClass.getDeclaredMethod("myMethod",(Class<?>[]) null);
return (ClassX)getter.invoke(beanObject, (Object[])null);
}
What I can further mention is that the fields I am trying to access are injected with the #Inject annotation, but I don't believe this is the problem as other instance fields, not injected, suffer of the same affection.
Normally I would use the getter but what I am trying to do here has a global impact on the application I am developing, which means that going back and modifying all affected classes to provide getters is a last measure solution. Also this application will be constantly modified and extended and I don't want to take the chance of the other developers not providing the getters, which will result in serious problems.
Thank you!
That's indeed expected behavior. The CDI managed bean instance is in essence a serializable proxy instance of an autogenerated class which extends the original backing bean class and delegates in all public methods further to the actual instance via public methods (like as how EJBs work). The autogenerated class looks roughly like this:
public CDIManagedBeanProxy extends ActualManagedBean implements Serializable {
public String getSomeProperty() {
ActualManagedBean instance = CDI.resolveItSomehow();
return instance.getSomeProperty();
}
public void setSomeProperty(String someProperty) {
ActualManagedBean instance = CDI.resolveItSomehow();
instance.setSomeProperty(someProperty);
}
}
As you see, there are no concrete fields. You should also have noticed the autogenerated class signature while inspecting the class itself too.
After all, you're going about this the wrong way. You should be using java.beans.Introspector API to introspect the bean and invoke getters/setters on bean instances.
Here's a kickoff example:
Object beanInstance = getItSomehow();
BeanInfo beanInfo = Introspector.getBeanInfo(beanInstance.getClass());
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
String name = property.getName();
Method getter = property.getReadMethod();
Object value = getter.invoke(beanInstance);
System.out.println(name + "=" + value);
}
This API respects like JSF and CDI the JavaBeans spec, so you don't need to fiddle around with raw reflection API and figuring/guessing the correct method names.
Unrelated to the concrete problem, depending on the concrete functional requirement for which you possibly incorrectly thought that this all would be the right solution, which you didn't tell anything about in the question, there may be even more better ways to achieve it than introspecting the bean instances.
I suspect the beans are getting proxied by the CDI and/or JSF implementation.
There is no reliable way of getting around this as the proxy implementation is server specific. Proxies are generated a runtime or application deployment time and at least for some implementations (eg weld) proxies do not have a reference to the bean itself but do have a reference to the internal classes it needs to get the bean and call the corresponding method.
About the only way I can think of doing this is to relax the security on your properties and hope that the prperty gets copied into the proxy reliable.
All of this is against the spirit of JavaEE and breaks all the rules of Object Orientation so I would strongly recommend against it.
I have used the standard factory pattern method before to create instances of classes (implementing a specific interface) using a Factory class, which has a "create" method, that returns the right instance based on the parameter passed to it (example snippet given below):
public class SimpleFactory {
public static SimpleObjectInterface getSimpleObject(int data) {
SimpleObjectInterface toReturn;
switch(data) {
case 1:
toReturn = new OneSimpleObject();
break;
case 2:
toReturn = new TwoSimpleObject();
break;
default:
toReturn = new DefaultSimpleObject();
break;
}
return toReturn;
}
}
Now I am using Guice in my project for dependency injection. My question is how can I achieve something like the above using Guice? Which implementation instance is needed is decided at runtime based on some user input.
I have looked at Provider and #Named annotations. But I don't understand how exactly it will help me.
In general for the problem where you want a factory that injects most dependencies, but still allows some client-supplied deps, you would use Factories by Assisted Injection.
However in your case this would lead to conditional logic in your factory, which is probably not ideal (it is explicitly discouraged in Guice modules).
I think for your situation a MapBinder would be ideal, and you wouldn't need a factory at all, since you're only switching on data type and not building anything really. In your module you configure a map of int (in your case) keys to impls of SimpleObjectInterface. Then in your main runtime class you inject the map, and when you need an instance of a simple object and have int data available, you call get(data) on the injected map.
I don't have an IDE on this machine, so I can't test the code, but from memory it would be something like below:
In your module:
public class MyModule extends AbstractModule {
protected void configure() {
MapBinder<Integer, SimpleObjectInterface> mapbinder
= MapBinder.newMapBinder(binder(), Integer.class, SimpleObjectInterface.class);
mapbinder.addBinding(1).toClass(OneSimpleObject.class);
mapbinder.addBinding(2).toClass(TwoSimpleObject.class);
}
}
In your app code:
#Inject
private Map<Integer, SimpleObjectInterface> simpleObjectMap;
...
void applicationCode() {
...
Integer data = getData();
SimpleObjectInterface simpleObject = simpleObjectMap.get(data);
...
}
Only issue here is you can't have the "default" binding that you had in your switch statement. Not sure of the best way to handle that, maybe you could assign a default impl in your app code if the object is still null after trying to instantiate it from the map binder. Or you could go back to assisted inject with conditional logic, but it's not really "assisted" injection if the sole dependency is client supplied.
See also: Can Guice automatically create instances of different classes based on a parameter?
Is there any way to require that a class have a default (no parameter) constructor, aside from using a reflection check like the following?
(the following would work, but it's hacky and reflection is slow)
boolean valid = false;
for(Constructor<?> c : TParse.class.getConstructors())
{
if(c.getParameterTypes().length == 0) {
valid = true;
break;
}
}
if(!valid)
throw new MissingDefaultConstructorException(...);
You can build an Annotation processor for that. Annotation Processors are compiler plugins that get run at compile time. Their errors show up as compiler errors, and may even halt the build.
Here is a sample code (I didn't run it though):
#SupportedAnnotationTypes("*") // needed to run on all classes being compiled
#SupportedSourceVersion(SourceVersion.RELEASE_6)
public class DefaultConstructor extends AbstractProcessor {
#Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (TypeElement type : ElementFilter.typesIn(roundEnv.getRootElements())) {
if (requiresDefaultConstructor(type))
checkForDefaultConstructor(type);
}
return false;
}
private void checkForDefaultConstructor(TypeElement type) {
for (ExecutableElement cons :
ElementFilter.constructorsIn(type.getEnclosedElements())) {
if (cons.getParameters().isEmpty())
return;
}
// Couldn't find any default constructor here
processingEnv.getMessager().printMessage(
Diagnostic.Kind.ERROR, "type is missing a default constructor",
type);
}
private boolean requiresDefaultConstructor(TypeElement type) {
// sample: require any JPA Entity to have a default constructor
return type.getAnnotation(Entity.class)) != null
|| type.getQualifiedName().toString().contains("POJO");
}
}
The annotation processor becomes even easier if you introduce an annotation (e.g. RequiresDefaultAnnotation).
Declaring the requirement of having a default qualifier
::I am also assuming that the OP asking for a mechanism that prevents accidental errors for developers, especially written by someone else.::
There has to be a mechanism to declare which classes require a default processor. Hopefully, you already have a criteria for that, whether it is a pattern in the name, pattern in the qualifier, a possible annotation, and/or a base type. In the sample I provided above, you can specify the criteria in the method requiresDefaultConstructor(). Here is a sample of how it can be done:
Based on a name pattern. TypeElement provide access to the fully qualified name and package name.
return type.getQualifiedName().toString().contains("POJO");
Based on an annotation present on the type declaration. For example, all Java Bean Entity classes should have a non-default constructors
return type.getAnnotation(Entity.class) != null;
Based on a abstract class or interface.
TypeElement basetype = processingEnv.getElements().getTypeElement("com.notnoop.mybase");
return processingEnv.getTypes().isSubtype(type.asType(), basetype.asType());
[Recommended Approach]: If you are using the basetype interface, I recommend mixing the annotation approach with the base type interface. You can declare an annotation, e.g. MyPlain, along with the meta annotation: #Inherited. Then you can annotate the base type with that annotation, then all subclasses would inherit the annotation as well. Then your method would just be
return type.getAnnotation(MyPlain.class) != null;
This is better because it's a bit more configurable, if the pattern is indeed based on type hierarchy, and you own the root class.
As mentioned earlier, just because it is called "annotation processing", it does mean that you have to use annotations! Which approach in the list you want to follow depends on your context. Basically, the point is that whatever logic you would want to configure in your deployment enforcement tools, that logic goes in requiresDefaultConstructor.
Classes the processor will run on
Annotation Processors invocation on any given class depends on SupportedAnnotationTypes. If the SupportedAnnotationTypes meta-annotation specifies a concrete annotation, then the processor will only run on those classes that contain such annotation.
If SupportedAnnotationTypes is "*" though, then the processor will be invoked on all classes, annotated or not! Check out the [Javadoc](http://java.sun.com/javase/6/docs/api/javax/annotation/processing/Processor.html#getSupportedAnnotationTypes()), which states:
Finally, "*" by itself represents the
set of all annotation types, including
the empty set. Note that a processor
should not claim "*" unless it is
actually processing all files;
claiming unnecessary annotations may
cause a performance slowdown in some
environments.
Please note how false is returned to ensure that the processor doesn't claim all annotations.
No. The above check can be easier rewritten as:
try {
MyClass.newInstance();
} catch (InstantiationException E) {
// no constructor
} catch (IllegalAccessException E) {
// constructor exists but is not accessible
?
You can employ PMD and Macker in order to guarantee architectural rules.
In partilar, Macker provokes compilation errors, breaking your build process when validations fail.
Macker extends some concepts made popular by PMD regarding validations of source code. A good example is when you'd like to guarantee that all classes from a package implements a certain interface.
So, if you are very paranoid (like me!) about verifying all possible architectural rules, Macker is really useful.
http://innig.net/macker/
Note: The website is not great. Colors will hurt your eyes... but the tools is very useful anyway.
Richard Gomes
http://www.jquantlib.org/