How to hide the internal structure of a Java API to the rest of the world

前端 未结 4 1304
不思量自难忘°
不思量自难忘° 2020-12-03 11:16

i am developing a Java Api to do things (secret, uhhhh ;).

Is there a way to hide classes, and the internal structure of my API?

What i found until now:

相关标签:
4条回答
  • 2020-12-03 11:32

    What do you mean by 'hide'?

    You can use the final modifier to stop people from extending methods and classes you don't want them to extend. If you want to stop people from decompiling your code, you can use code obfuscation and if you want to take it even further, you can use anonymous inner classes that implement interfaces.

    0 讨论(0)
  • 2020-12-03 11:40

    There are two solutions to your question that don't involve keeping all classes in the same package.

    The first is to use the Friend Accessor/Friend Package pattern described in (Practical API Design, Tulach 2008).

    The second is to use OSGi.

    Related Questions: 1, 2, 3, and 4.

    0 讨论(0)
  • 2020-12-03 11:56
    • You can try and make only your interfaces public. Have a look at the Factory Pattern.
    • Alternatively, you can implement you're application in OSGI.

    Neither of these methods would allow you to hide the implementation completely to someone who really wanted to see it. Someone could still use a decompiler to examine you .class files, or even examine the code in memory.

    If you really need to protect your implementation in this way, then a good approach would be to only allow access to your application as a remote service and host it on a secure machine.

    0 讨论(0)
  • 2020-12-03 11:57
    • Use interfaces to define what your app does
    • Create a main entry point to accesses services, returning interfaces only
    • I wouldn't bother about actually hiding the implementation classes. You can never really hide them in Java, and those who are technically interested might just start your app with a debugger. Just provide no public constructors, for example

    Regarding this comment:

    Sean, would you elaborate a little more on your answer? ...

    One way to implement my second bullet point I mean using a Service Lookup class, e.g.

    public class Lookup {
        private static final Foo foo = new FooImpl();
        public static Foo getFoo() { 
            return foo; 
        }
    }
    

    Foo is an interface, FooImpl an implementation class (which can be package private if you want to enforce that it can't be instantiated by clients)

    0 讨论(0)
提交回复
热议问题