有沒有辦法創建一個接口限制訪問特定的方法?限制方法調用到一個特定的類(在一個接口範圍內)
例子:
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");
}
}
可以做的伎倆,但這將被改寫後使這不會真正解決問題。
看起來你的代碼設計初衷是錯誤的。你能否提供更多的上下文?向我們展示一個您的界面的示例實現(包括之後應如何使用該「組件」)。 –
我在你的方法實現中看不到任何'component'的用法。 – Arpit
@TagirValeev這當然是錯的。整個程序都很混亂,但我只能訪問它。實現類是一個自定義的輸入監聽器(鍵綁定),它有一個用於源的Component,一個實例如果傳遞給另一個Object,女巫應該設置Component,但只有當Object是一個特定類的實例。簡而言之,隨機用戶不應該爲輸入類設置源「Component」。 PS:我知道這是令人困惑,但這是我能做的最好的解釋情況(對不起) –