我正在開發一種可以編譯為 JVM 字節碼的編程語言,它高度依賴接口作為類型。我需要一些方法來使接口私有,但讓其他代碼仍然能夠訪問它,但不能實現它。我正在考慮使用帶有私有構造函數的抽象類,因此只有同一文件中的類才能訪問它。唯一的問題是一次擴展多個抽象類是不可能的。例如,一個簡單的編譯程序的結構是這樣的:// -> Main.javapublic class Main { public static MyInteger getMyInteger() { return new MyIntegerImpl(10); } public static void main(String[] args) {} private interface MyInteger { public int getValue(); } private static class MyIntegerImpl implements MyInteger { private final int value; public int getValue() { return value; } public MyIntegerImpl(int value) { this.value = value; } }}還有另一個文件,其中存在問題:// -> OtherFile.javapublic class OtherFile { public static void main(String[] args) { Main.MyInteger myInteger = Main.getMyInteger(); //Error: The type Main.MyInteger is not visible. System.out.println(myInteger.getValue()); } //I do not want this to be allowed public static class sneakyInteger implements Main.MyInteger { //Error(Which is good) public int getValue() { System.out.println("Person accessed value"); return 10; } }}我想這樣做的原因是,一個人不能通過提供自己的實現來搞亂任何其他人的代碼,而這些實現應該只能由其他人實現。任何幫助將非常感激。
1 回答
慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
我很確定您應該再次考慮您要做什么并更改方法,但是您問題的答案是向接口添加一些空void方法,該方法正在獲取特定于包裝器類的內部private類的參數
public class Test {
private class InnerPrivateClass {
private InnerPrivateClass() {}
}
public interface MyInteger {
int getValue();
void accept(InnerPrivateClass c);
}
private class MyIntegerImpl implements MyInteger {
@Override
public int getValue() {
return 0;
}
@Override
public void accept(InnerPrivateClass c) {}
}
}
但是,正如我所說,我不喜歡這樣,對我來說,這意味著你的想法被打破了
添加回答
舉報
0/150
提交
取消
