本文介紹了如何使(靜態(tài))初始化程序塊嚴(yán)格tfp?的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
在重構(gòu)一些代碼時(shí),我偶然發(fā)現(xiàn)了這個(gè)奇怪的地方。似乎不可能在不影響整個(gè)類的情況下控制初始值設(shè)定項(xiàng)的Structfp屬性。示例:
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
}
}
從JLS, Section 8.1.1.3我推測,如果類將使用rangtfp修飾符聲明,則初始值設(shè)定項(xiàng)將是strictfp。但它也表示,它會(huì)使所有方法隱式嚴(yán)格執(zhí)行<tfp:
strictfp修飾符的作用是使類聲明中的所有浮點(diǎn)或雙精度表達(dá)式(包括變量初始值設(shè)定項(xiàng)、實(shí)例初始值設(shè)定項(xiàng)、靜態(tài)初始值設(shè)定項(xiàng)和構(gòu)造函數(shù))都顯式為FP嚴(yán)格的(§15.4)。
這意味著類中聲明的所有方法和類中聲明的所有嵌套類型都是隱式嚴(yán)格的。
因此,靜態(tài)初始值設(shè)定項(xiàng)不接受修飾符,當(dāng)應(yīng)用于整個(gè)類時(shí),一切都變得嚴(yán)格?由于沒有關(guān)鍵字OBLISTER,所以這是不可能實(shí)現(xiàn)的?
那么,我是不是應(yīng)該使用靜態(tài)方法來保持初始值設(shè)定器塊的主體,以實(shí)現(xiàn)對(duì)嚴(yán)格性的精確控制?
推薦答案
使用以下要求:
初始化代碼調(diào)用一次
MyClass.myMethod
方法是非嚴(yán)格浮點(diǎn)
類API中沒有方法,
且初始化代碼為嚴(yán)格浮點(diǎn)
.這就足夠了:
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
}
}
如果您將類的靜態(tài)成員視為單獨(dú)的單個(gè)對(duì)象中的對(duì)象,則上面的示例看起來很自然。我認(rèn)為這與Single Responsibility Principle配合得很好。
這篇關(guān)于如何使(靜態(tài))初始化程序塊嚴(yán)格tfp?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,