非默认构造函数java,在java中需要一个默认构造函数?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值