views:

556

answers:

3

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(...);
+9  A: 

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:

  1. Based on a name pattern. TypeElement provide access to the fully qualified name and package name.

    return type.getQualifiedName().toString().contains("POJO");
    
  2. 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;
    
  3. Based on a abstract class or interface.

    TypeElement basetype = processingEnv.getElements().getTypeElement("com.notnoop.mybase");
    return processingEnv.getTypes().isSubtype(type.asType(), basetype.asType());
    
  4. [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, 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.

notnoop
Yes, except that would require an annotation placed on class (or constructor). And how would you enforce that? :-)
ChssPly76
Annotations work when you provide a base class or interface which must be used. This is a quite elegant solution for the problem that one cannot enforce a constructor in an interface. Other than that, your solution using try/catch is the most elegant way I know to handle this. Albeit this only works at runtime.
frenetisch applaudierend
@ChssPly76, almost correct. He can create any criteria he'd like to figure out whether a class needs to have a default constructor.
notnoop
@notnoop - can you elaborate, please? How would I go about enforcing that a particular class has a constructor using annotation processor without requiring user placing a specific annotation on it first? I'm genuinely interested here - if it's possible to do magic like Lombok that'd be fantastic
ChssPly76
I was wondering the same thing. Seems to me the annotation is worthless unless the person writing the class knows to use it, in which case they would probably know to just write a default constructor. You cant define an abstract constructor in the base class (I dont think)
jdc0589
@notnoop = I could be way off, but are you talking about writing a class level annotation/processor, and actually making the annotation at the class level of the abstract/base class definition?
jdc0589
@notnoop - options #2 - #4 listed above all rely on enforcement of something else (annotation / base class). Option #1 does not - but I don't think it will work. My understanding is that annotation processor will NOT be invoked for class that is neither annotated nor extends another annotated class (impements interface). Am I wrong? If not, this is nothing but indirection - requiring public empty constructor is no different from requiring an annotation on a class.
ChssPly76
@ChssPly76, No! Annotation Processor can be invoked on all classes (updated post). Basically, any logic you have in your deployment script can be done in your annotation processor. You can even check classes in classpath that don't have source code available. For that though, please start a new question or email me offline at my username `@gmail.com`
notnoop
Thanks, I'll run a test.
ChssPly76
+5  A: 

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
?
ChssPly76
Good idea, didnt think of that. If I decide its actually worth enforcing, I will probably do it that way. Its not really necessary to enforce it for my purpose though, I was just curious.
jdc0589
I am actually enforcing it for certain 3rd-party plug-ins we use. The above (among other checks) runs as part of verification process within deployment script. I'm very interested to see whether notnoop's solution pans out, though (with no annotation dependency) - it'd definitely make some things easier.
ChssPly76
except that this approach actually runs the constructor if it is present. A side effect you might not want
Michael Wiles
A: 

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 M: 44(77)9955-6813 http://tinyurl.com/frgomes twitter: frgomes

JQuantlib is a library for Quantitative Finance written in Java. http://www.jquantlib.org/ twitter: jquantlib

Richard Gomes