Dur*_*dal 5 java scope declaration strictfp
在重构一些代码时,我偶然发现了这个奇怪的问题.在不影响整个类的情况下,似乎无法控制初始化程序的strictfp属性.例:
public class MyClass {
public final static float[] TABLE;
strictfp static { // this obviously doesn't compile
TABLE = new float[...];
// initialize table
}
public static float[] myMethod(float[] args) {
// do something with table and args
// note this methods should *not* be strictfp
}
}
Run Code Online (Sandbox Code Playgroud)
从JLS开始,第8.1.1.3节我认为如果使用strictfp修饰符声明类,初始化器将是strictfp .但它也说它使所有方法隐含严格:
strictfp修饰符的作用是使类声明中的所有float或double表达式(包括在变量初始化器,实例初始值设定项,静态初始化器和构造函数中)都是明确的FP-strict(第15.4节).
这意味着在类中声明的所有方法以及在类中声明的所有嵌套类型都是隐式strictfp.
因此,静态初始值设定项不接受修饰符,当应用于整个类时,一切都变为strictfp?由于strictfp关键字没有反面,这是不可能实现的?
那么,我是否使用静态方法来保持初始化程序块的主体以实现对strictfp'dness的精确控制?
使用以下要求:
MyClass.myMethod方法是非严格浮点,...这就足够了:
class MyClass {
//1) initialized/called once
public final static float[] TABLE = MyClassInitializer.buildSomething();
public static float[] myMethod(float[] args) {
//2) non-strict
}
}
//3) doesn't "pollute" the MyClass API
class MyClassInitializer {
strictfp [static] float[] buildSomething() { //4) strictfp here or on the class
//TODO: return something
}
}
Run Code Online (Sandbox Code Playgroud)
如果您将类的静态成员视为单独的单例对象中的对象,则上面的示例看起来很自然。我认为这非常符合单一职责原则。