2015-07-04 18 views
0

有沒有辦法創建一個接口限制訪問特定的方法?限制方法調用到一個特定的類(在一個接口範圍內)

例子:

public interface MyInterface { 

    /* 
    * I want to restrict access to this(and only this) method so only 1 specific class 
    * can call it. Is there a way of doing that? 
    */ 
    public void setComponent(Component); 

    ...other methods... 

} 

編輯:

類似:

public default void setComponent(Component component) { 
    StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 
    if(!stacktrace[1].getClassName().equals("MyClassName")){ 
     throw new IllegalStateException("Method should not be called explicitly"); 
    } 
} 

可以做的伎倆,但這將被改寫後使這不會真正解決問題。

+0

看起來你的代碼設計初衷是錯誤的。你能否提供更多的上下文?向我們展示一個您的界面的示例實現(包括之後應如何使用該「組件」)。 –

+0

我在你的方法實現中看不到任何'component'的用法。 – Arpit

+0

@TagirValeev這當然是錯的。整個程序都很混亂,但我只能訪問它。實現類是一個自定義的輸入監聽器(鍵綁定),它有一個用於源的Component,一個實例如果傳遞給另一個Object,女巫應該設置Component,但只有當Object是一個特定類的實例。簡而言之,隨機用戶不應該爲輸入類設置源「Component」。 PS:我知道這是令人困惑,但這是我能做的最好的解釋情況(對不起) –

回答

1

答案是。因爲默認Interface中的方法是公開的。如果你想實現,使Abstract類聲明的方法protected

public abstract class MyAbstractClass { 


    protected void setComponent(Component); 

    ...other methods... 

} 
+0

我知道我可以重新設計它以延長課程,但對我來說這不是最好的解決方案。我希望能跟蹤堆棧跟蹤,並從界面中找到調用者類。與此問題是我必須實現一個默認的身體將被重寫,所以它不會真的解決問題。 –

+0

「跟蹤棧跟蹤並從界面中找到調用者類」是什麼意思? – Arpit

+0

請參閱該問題的版本。 –

0

如果您afraiding你的方法得到重寫,使用決賽,然後在setCompomonet()結束時,調用一個新的抽象保護方法,像realSetCompoment()。

+0

這個問題需要改進。 – Envil

+1

@Envil抱歉,我是新來的。現在好嗎? –

相關問題