java 计算协方差_Java的深度:通过协方差暴露的API泄漏
java 計(jì)算協(xié)方差
Java有時(shí)可能非常棘手,特別是在API設(shè)計(jì)中。 讓我們看一個(gè)非常有趣的展示柜。 jOOQ強(qiáng)烈地將API與實(shí)現(xiàn)分開(kāi)。 所有API都在org.jooq包中,并且是公共的。 大多數(shù)實(shí)現(xiàn)是在org.jooq.impl包和package-private中。 只有工廠和一些專(zhuān)用的基礎(chǔ)實(shí)現(xiàn)是公開(kāi)的。 這允許非常強(qiáng)大的包級(jí)封裝,幾乎只向jOOQ用戶(hù)公開(kāi)接口。包級(jí)封裝的簡(jiǎn)化示例
大致來(lái)說(shuō),jOOQ如何建模SQL表。 (過(guò)于簡(jiǎn)化的)API:
還有兩個(gè)(過(guò)于簡(jiǎn)化的)實(shí)現(xiàn)類(lèi):
package org.jooq.impl;import org.jooq.Table;/*** Base implementation*/ abstract class AbstractTable implements Table {@Overridepublic Table join(Table table) {return null;} }/*** Custom implementation, publicly exposed to client code*/ public class CustomTable extends AbstractTable { }內(nèi)部API的公開(kāi)方式
假設(shè)內(nèi)部API在協(xié)方差方面有一些技巧:
abstract class AbstractTable implements Table, InteralStuff {// Note, this method returns AbstractTable, as it might// prove to be convenient to expose some internal API// facts within the internal API itself@Overridepublic AbstractTable join(Table table) {return null;}/*** Some internal API method, also package private*/void doThings() {}void doMoreThings() {// Use the internal APIjoin(this).doThings();} }乍一看,這看起來(lái)很安全,是嗎? AbstractTable是包私有的,但CustomTable對(duì)其進(jìn)行了擴(kuò)展并繼承了其所有API,包括“ AbstractTable join(Table)”的協(xié)變方法重寫(xiě)。 這會(huì)導(dǎo)致什么? 查看以下客戶(hù)端代碼
package org.jooq.test;import org.jooq.Table; import org.jooq.impl.CustomTable;public class Test {public static void main(String[] args) {Table joined = new CustomTable();// This works, no knowledge of AbstractTable exposed to the compilerTable table1 = new CustomTable();Table join1 = table1.join(joined);// This works, even if join exposes AbstractTableCustomTable table2 = new CustomTable();Table join2 = table2.join(joined);// This doesn't work. The type AbstractTable is not visibleTable join3 = table2.join(joined).join(joined);// ^^^^^^^^^^^^^^^^^^^ This cannot be dereferenced// ... so hide these implementation details again// The API flaw can be circumvented with castingTable join4 = ((Table) table2.join(joined)).join(joined);} }結(jié)論
篡改類(lèi)層次結(jié)構(gòu)中的可見(jiàn)性可能很危險(xiǎn)。 注意以下事實(shí):在接口中聲明的API方法始終是公共的,而不管涉及非公共偽像的任何協(xié)變實(shí)現(xiàn)。 如果API設(shè)計(jì)人員無(wú)法正確處理API用戶(hù),這可能會(huì)很煩人。
在下一版的jOOQ中已修復(fù)
參考: Java的深度:在JAVA,SQL和JOOQ博客中, JCG合作伙伴 Lukas Eder 通過(guò)協(xié)方差暴露了API泄漏 。
翻譯自: https://www.javacodegeeks.com/2012/05/depths-of-java-api-leak-exposed-through.html
java 計(jì)算協(xié)方差
總結(jié)
以上是生活随笔為你收集整理的java 计算协方差_Java的深度:通过协方差暴露的API泄漏的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: B 社陶德:《星空》会推出 DLC,但何
- 下一篇: 如何鉴别银行转账回执真假?