Is it really impossible to hide some classes in a jar file?
I wanted not to allow direct instantiation of the classes to keep it more flexible. Only the factory (or a facade) should be visible of this jar.
Is there any other way than solve this problem than creating two projects?
(Two projects: the first one contains the classes (implementation) and the other one references to the first one and contains the factory; later only the second one will be referenced)
I'm understanding you're not looking to hide the actual classes, just prevent their construction outside a factory class. This I think can be quite easily achieved by using package private (default) visibility in the class constructors. The only limitation is that you'll need to have the classes and the factory in the same package so in a medium to large codebase things may get unnecessarily complex.
If I understand your question correctly, you would like to make sure that users of your library are forced to use your factory to instantiate their objects rather than using the constructors themselves.
As I see it there are two possibilities, one of which is silly but usable in few, specific cases, and the other one is the most practical and probably most commonly used way of doing it.
You could make all your classes into
private inner classes of the
factory. This would work if you had
one factory per class, but is hardly
workable if you have a lot of
different classes being managed
through one factory.
You could use the protected access modifier to
restrict access to your class
constructors. This is common
practice when using the factory
pattern.
I think you will have either compiler failure or warning if your public factory method try to return something which is "hidden".
No, you can not hide a public class without reimplementing your own ClassLoader or using OSGi or anything similar.
What you can do is to separate interface api from the implementation, e.g. have one project which contains only the interfaces and another porject which contains the implmentations. However, you still cannot hide the implementation classes.
Obfuscation can help you somehow.
With standard classloaders and plain old jar files, this is not possible. OSGi has this concept of making visible only some packages to another bundle(i.e. separation of public api and internal implementation).
If you are using eclipse, you may enforce such rules with this
If I understand you correctly when you say "not to allow direct instantiation of the classes to keep it more flexible", a properly executed facade pattern will handle this.
Restrict the constructors of all the classes you want to hide to package scope. Open the facade class to public scope.
http://mindprod.com/jgloss/packagescope.html
"If you have a variable or method in
your class that you don’t want clients
of your class directly accessing,
don’t give it a public, protected or
private declaration. Due to an
oversight in the design of Java, you
can’t explicitly declare the default
“package” accessibility. Other members
of the package will be able to see it,
but classes outside the package that
inherit from yours, won’t. The
protected accessibility attribute
offers slightly more visibibily. A
protected method is visible to
inheriting classes, even not part of
the same package. A package scope
(default) method is not. That is the
only difference between protected and
package scope. "
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. There is an article here explaining how OSGi accomplishes this.
Related Questions: 1, 2, 3, and 4.
You can do such magics with a custom class loader but:
the correct separation will be available only in a project staffed with your class loader;
it's really doubtful that the effort to create such loader is worthy.
In such situations I would do something similar to what we may see in the standard Java. E.g.you see javax.xml.stream.XMLInputFactory but somewhere you have com.sun.xml.internal.stream.XMLInputFactoryImpl. It is perfectly compilable if you write:
new com.sun.xml.internal.stream.XMLInputFactoryImpl()
though you will hardly do it :-) With a system property you may control the actual implementation that is being loaded. To me such approach is fine in many situations.
I hope I have understood your question correctly ;)
Cheers!
Related
How to make a member of a class to be accessible only in subclasses in any packages? Protected is not a solution since it will open the member to other non subclasses classes.
Java does not provide absolute encapsulation. Some amount of discipline is required on the part of the programmer - both the original designer and anyone that uses a published API - to abide by some rules that are outside of the language. Regarding member access, you have identified one such case. What you want is not possible in Java.
Just to put this in broader perspective, I'd point out that even private members can be accessed by other classes if a programmer is willing to go far enough to do it. Calls made via JNI do not have to respect any of the access modifiers. See, e.g., Can a native method call a private method?
Other examples of out-of-language norms include the contract for equals/hashCode, which must be met for classes to behave well with respect to collections but is not enforced at the level of the language.
I understand why you want to do this; however, Java simply does not provide that capability.
You could do abstract class with protected member, and implement it in another packages. Consider you created some lib and design extensability for certain things. Later users of your lib will implement realizations of your class and has access to protected member and in same time not able to create implementation classes in your package. In example FilterReader class, it design for extensibility, after you implement it in somewhere in your code outside java.io package that protected fields and methods will be private to other classes in your package.
What you are trying to achieve ist not possible during to acces control:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
You may rethink your software design, since yout problem is caused by architecture.
please be more specific in your question for getting further answer.
Solving your problem may cause sideeffects and is not in a OOD manner.
The only way to acces the private member is using an getter method with same visibilty issuses.
Say I have an abstract class AbstractBarrelComponent that extends the Component class. The class uses a class named Barrel for some imaginary purpose.
Where should my Barrel class reside, if the only classes that would/can/should ever use it are the AbstractBarrelComponent and its subclasses?
By "reside" I mean should the class be in its own file, Barrel.java, or should it be a package-protected class in AbstractBarrelComponent.java? Is there a common convention for this kind of situation?
Different programmers and organisations use different standards for this and I don't think there is one right answer. The important thing is to pick a standard and stick to it.
My personal standard is that inner classes are always private. If a subclass needs access to it then it either should be in a outer protected class or access to its methods should be made available via delegation. The only downside to this is that you end up with more small classes. But, frankly, modern clean coding style relies on good IDEs that make it easy to navigate around your code so the need to group classes for navigation has mostly gone away.
As an aside, I feel it's unfortunate that the designers of Java did not make a distinction between protected for access by subclasses and protected for access by all classes in the same namespace. These are really quite separate use cases. In your situation there's a tendancy to make it an inner protected classes rather than an outer protected classes to restrict access to subclasses. It would have been better if there was a separate keyword for these two uses.
It's common to have an object used application wide.
What are the different patterns / models / ways to share an object through an application?
Is defining a "main class", then setting a member variable and extending all other classes from this "main class" a good way? Is creating a static class probably the better and cleaner way? What's your prefered pattern?
It's common to have an object used application wide. What are the different patterns / models / ways to share an object through an application?
One common way is to use the singleton pattern. I would avoid that though.
Is defining a "main class", then setting a member variable and extending all other classes from this "main class" a good way
Absolutely not. Aside from anything else, if it's an instance variable then it wouldn't be "shared" with instances of your other classes anyway. It's also a complete abuse of inheritance which would certainly bite you hard in any application of significant size - your other classes wouldn't logically have an inheritance relationship with your "main" class, would they? As a general rule, inheritance should only be used when it's really appropriate - not to achieve a quick fix.
What's your prefered pattern?
Dependency injection. When your application starts up, create all the appropriate objects which need to know about each other, and tell them (usually in the constructor) about their dependencies. Several different objects can all depend on the same object if that's appropriate. You can use one of the many dependency injection frameworks available to achieve this easily.
Dependency injection generally works better than using singletons because:
The class itself doesn't know whether or not the dependency is actually shared; why should it care?
Global state makes unit testing harder
Each class makes its dependencies clearer when they're declared - it's then easier to navigate around the application and see how the classes relate to each other.
Singletons and global factories are more appropriate when they're for things like logging - but even then, it means it's relatively hard to test the logging aspects of a class. It's a lot simpler to create a dependency which does what you need it to, and pass that to the object under test, than it is to add ways of messing around with a singleton (which usually remains "fixed" after initialization).
If you use a framework like Spring which has dependency injection, you can get all the benefits of "global" objects for free without needing to explicitly define them. You just create a reference to them in your application context and you can inject them into any object you'd like without worrying about issues with synchronizing.
Singleton pattern, AFAIK the preferable way in software engineering.
I believe what you are looking for is the Singleton Pattern. With this pattern you are ensured that only one instance of a class can be created in memory.
Example:
public class mySingletonClass {
private static mySingletonClass singleObject;
// Note that the constructor is private to prevent more than one
//instance of the class
private SingletonObjectDemo() {
// Optional Code
}
public static mySingletonClass getSingletonObject() {
if (singleObject == null) {
singleObject = new mySingletonClass();
}
return singleObject;
}
}
That said, you should try to avoid using it; but there are some acceptable cases, one of which is here.
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:
Using inner classes (ugly way, i do not want to put all in on class file)
All classes in one package so that i can use the "package"-visibilty (also ugly, i need more packages)
Example:
---
package net.my.app;
//this is the Public Access
class MyPublicClass{
public void somePublicFunction(){
//access to not visibil classes
}
}
---
package net.my.app.notvisible:
//this is what i want to hide
class MyNOTPublicClass{
...
}
---
Any ideas?
Thank you!
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.
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)
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.
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.
I was wondering how to package the factories that I have in my application. Should the Factory be in the same package as the classes that use it, in the same package as the objects it creates or in its own package?
Thanks for your time and feedback
Usually factories are in the same package as the objects they create; after all their purpose is to create those objects. Usually they are not in a separate package (there is no reason for that). Also having the factory be in the same package as the objects they create allows you to exploit package visibility.
The whole point of a Factory is to have a configurable way to create implementation instances for interfaces. The convention to have the factory in the same package as the implementation classes it provides adds a completely unnecessary restriction you're unlikely to meet in the future. Also if the implementation returned is not the same across all contexts, it makes even less sense to have it in the same package.
For example, imagine a service lookup factory that is shared between the client and server part of an application, which returns a client side implementation (which resides in a client-only package) on the client, and a server side implementation (in a server-only package) when called from within the server's runtime.
Your factory may even be configurable (we do this by having a XML file which defines which implementation class to return for which interface), so the implementation classes can easily be switched, or different mappings can be used for different contexts.
For example, when unit testing we use a configuration which returns mockup implementations for the interfaces (do be able to do unit tests that are not integration tests), and it would make no sense at all to require those mockup implementations to be in the same package as the factory, as they're part of the testing code rather than the runtime code.
My recommendation:
Don't add any package restrictions on
the implmentation classes, as you
don't know which implementations are
used in the future, or in different
contexts.
The interfaces may be in the same
package, but this restriction is also
unnecessary and only makes the
configuration rigid.
Configurable factories (such as a service lookup) can be reused and
shared across projects when the
interface/implementation mapping
isn't hardcoded. This point alone
justifies having the factory
separated from both the interfaces
and the implementation classes.
The unit of reuse is the unit of release. This means there shouldn't be coupling across packages, as the package is generally the lowest granularity of release. When you organize a package, imagine yourself saying, "here's everything you need to use these classes."
I like to put the factory in the package it is creating objects for, naming is key here, if naming is clear and transparent it will help maintenance effort down the line.
For example an action factory could be structured as:
package org.program.actions
interface org.program.actions.Action
enum org.program.actions.ActionTypes
factory org.program.actions.ActionFactory (or .ActionManager)
action implementation classes org.program.actions.LogAction, etc.
Following patterns like this throughout projects help project members to find classes where they actually are located in projects they haven't been involved in before.
That wholly depends on the way you're intending to use said factories. Sometimes it makes sense to put a factory in its own package.
You might for example have an interface, foo.bar.ui.Interface. You want to have different implementations of that interface, one for AWT, one for Swing, one for the console, etc. Then it would be more appropriate to create a foo.bar.ui.swing.SwingInterfaceFactory that creates a foo.bar.ui.swing.SwingInterface. The factory for the foo.bar.ui.awt.AWTInterface would then reside in foo.bar.ui.awt.AWTInterfaceFactory.
Point is, there is no always-follow-this rule. Use whatever is appropriate for your problem.
why not. make it as close as possible if there is no other objections. actually why not
public interface Toy
{
static class Factory
{
public static final Toy make() { ... }
}
}
Toy toy = Toy.Factory.make();
HA!
but make() shouldn't statically depend on subclasses of Toy, that would be bad. it can do some dynamic magic, depends on your factory strategy.