简体   繁体   中英

How can I make an Interface Private but used between two classes?

I want to create a private Interface in Class A and have it implemented by Class B. My intention is to have a way for Class A to call a method set on class B that NO ONE else can call. They are in separate file in separate packages. Anyone have any ideas?

The best you can achieve is to give the interface package level visibility and move Class A and B into the same package.

This doesn't stop someone adding another class into the same package in the future, thus giving it access to the interface.

short answer is redesign your class structure.

But if you really need to, consider to use reflex feature in java. and you can inject the method although not recommended.

Disclaimer: not a Java programmer.

But if you want to leverage a type system to get compile-time errors... there are often tricks by introducing a new data type as a sort of "access token" or "dummy parameter". Make it hard to get ahold of a value of that type, but require a value of that type as a parameter in the interface.

Yet introducing a hoop like that winds up being about as contrived as renaming your methods alarming things like DoFooActionOnClassB_ButDontCallUnlessYouAreClassA . I think one usually finds that in a good design, this "dummy type" isn't a dummy type at all... but a capture of the context and state that you should have had in the first place.

I understand that you want to have methods on class B which can only be called from class A. One way would be deferring the real check until runtime but let the compiler make it hard to do the wrong thing. So you could try using a secret which only class A can have in order to protect the method in class B.

public class A {
    private static final PrivateA PROOF = new PrivateA();
    public static class PrivateA {
        private PrivateA() { }
        // only A can extend PrivateA
    }
    public static void main(String[] args) {
        new B().methodForAOnly(PROOF, "A");
    }
}

Here A's PrivateA is a type which only A can instantiate or extend, and B knows about that...

public class B {
    public void methodForAOnly(PrivateA proof, String param) {
        if (proof == null) throw new NullPointerException();
        // do something
        System.out.println(param);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM