Потребовать конструктора по умолчанию в Java?

Глава 1 "Искусства Программирования" имеет целью обеспечивать точно это.

12
задан jdc0589 18 November 2009 в 22:05
поделиться

3 ответа

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. [Рекомендуемый подход]: Если вы используете интерфейс базового типа, я рекомендую смешивать подход аннотации с интерфейсом базового типа. Вы можете объявить аннотацию, например MyPlain , вместе с метааннотацией: @Inherited . Затем вы можете аннотировать базовый тип этой аннотацией, тогда все подклассы также унаследуют аннотацию. Тогда ваш метод будет просто

     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 набор всех типов аннотаций, включая пустой набор. Обратите внимание, что процессор не должен заявлять "*" , если это не собственно обработка всех файлов; заявка на ненужные аннотации может вызвать снижение производительности в некоторых

Обратите внимание, как возвращается false , чтобы гарантировать, что процессор не запрашивает все аннотации.

22
ответ дан 2 December 2019 в 05:15
поделиться

Нет. Вышеупомянутую проверку можно проще переписать как:

try {
  MyClass.newInstance();
} catch (InstantiationException E) {
  // no constructor
} catch (IllegalAccessException E) {
  // constructor exists but is not accessible
?
6
ответ дан 2 December 2019 в 05:15
поделиться

Вы можете использовать PMD и Macker, чтобы гарантировать архитектурные правила. В partilar Macker вызывает ошибки компиляции, нарушая процесс сборки при проверке неудача.

Macker расширяет некоторые концепции, ставшие популярными благодаря PMD в отношении валидации исходного кода. Хороший пример - это когда вы хотите гарантировать, что все классы из пакета реализуют определенный интерфейс.

Итак, если вы очень параноик (как и я!) Относитесь к проверке всех возможных архитектурных правил, Macker действительно полезен.

http://innig.net/macker/

Примечание: сайт не очень хорош. Цвета режут глаза ... но инструменты все равно очень полезны.

Ричард Гомес http://www.jquantlib.org/

1
ответ дан 2 December 2019 в 05:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: