Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 465735
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T23:24:27+00:00 2026-05-12T23:24:27+00:00

Is there any way to require that a class have a default (no parameter)

  • 0

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(...);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T23:24:28+00:00Added an answer on May 12, 2026 at 11:24 pm

    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](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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 366k
  • Answers 366k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Try this: public class Microwave { public event EventHandler<EventArgs> DoorClosed;… May 14, 2026 at 4:34 pm
  • Editorial Team
    Editorial Team added an answer You already have the solution with your second attempt, you… May 14, 2026 at 4:34 pm
  • Editorial Team
    Editorial Team added an answer You can use the menu_valid_path() function for this. This returns… May 14, 2026 at 4:34 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.