【发布时间】:2021-09-29 12:10:16
【问题描述】:
这是有线的,但你能做到吗?
我想使用无参数构造函数(所以开发依赖于我的框架不需要扩展构造函数),但我想在字段中使用 final。所以:
Annotation.java
public @interface Annotation {
String value();
}
父类.java
public abstract class Parent {
public final String name;
// this will cause you must extends constructor in any sub class
public Parent(Annotation annotation){
this.name = annotation.value();
}
}
接口定义
public abstract class Define extends Parent {
// You can't do that:
// Cannot reference 'this' before supertype constructor has been called
public Define (){
this(this.getClass().getAnnotation(Annotation.class).value());
}
// You can do that, but not working
// Define is point at Define as is rather I hope the sub class MyModule
public Define (){
this(Define.class.getAnnotation(Annotation.class).value());
}
public Define (Annotation annotation){
super(annotation); // You must extend this
}
public abstract void foo();
}
我希望开发者可以像这样使用我的框架:
public class MyModule extends Define {
public void foo(){
// foo bar
}
}
但是由于Cannot reference 'this' before supertype constructor has been called,你必须写:
@Annotation
public class MyModule extends Define {
// my framework using scan an IoC auto invoke
public MyModule(Annotation annotation){
super(annotation.value())
}
public void foo(){
// foo bar
}
}
悖论是name是写在注解中,而this必须在newInstance之后。所以这个问题更像是:
子类如何getClass()?
所以唯一的解决方案是放弃 final 字段并使用类似 init() 的东西?
【问题讨论】:
标签: java annotations java-annotations