Package equivalent visibility modifier in Kotlin - java

I'm writing a program in which I'm using the factory pattern. I have an interface called AssetFundCalculator and a class named AssetFundCalculatorImpl which implements the interface.
The AssetFundValidator class validates some inputs, and is able to instantiate a valid AssetFundCalculatorImpl.
I'd like if the rest of the program would only know about the interface, and not about the AssetFundCalculatorImpl, so that only the AssetFundValidator could instantiate it.
My package structure is looking like this:
In Java, I would give package visibility modifier to the AssetFundCalculatorImpl class, or it's constructor, and it would solve the issue, but in Kotlin, there is no package visibility modifier.
Is there a solution to this?
I don't want to put this code to a separately compiled module, so the internal modifier is not going to work.

You can put AssetFundValidator and AssetFundCalculatorImpl into the same file and mark AssetFundCalculatorImpl as private. In that case it will only be accessible to code in the same file, including AssertFundValidator, but not to any code in other parts of the program.

Related

Best access modifier for MODULE variable in any class file in java?

Ok, let me start it with the following example to get a brief example
public class ClassA{
______ static final String MODULE = "[ClassA]";
}
in the blank space, I came across many code snippet it has some times public or protected or private but could not understand the which one is the best and why?.I know protected is best for subclass implementation but then subclass to has MODULE variable.
basically MODULE is used in logging activities like for example
System.out.println(MODULE+"given message");
in-short which is best way to use for accessing?
Like anything, you should give it the strictest access level that makes sense.
If it will only be used inside the class, use private. If it will only be used inside the package, use package access. If it could be used in subclasses, use protected. If it could be used by anyone, use public.
This applies to every class member in every programming language - it is by no means specific to fields named MODULE in Java.
Basically MODULE is used in logging activities...
Then I would suggest to make it private, because it will not be used outside the class (assuming that other classes have similar static constants).

Non-Public Static Nested Class?

I am trying to write tests for a piece of code that uses the inner class of the following object as an input (I've generalized the names).
public class MockOuterClass implements OuterClass, Mock {
static class MockInnerClass implements InnerClass {
//fields and methods of the nested class
}
//methods of the outer class
}
Now since the inner class does not have a visibility tag, it defaults to "protected." Here lies my issue: since my tests and source code are in separate packages, how can I create an instance of this inner object? I attempted this:
MockOuterClass.MockInnerClass test = new MockOuterClass.MockInnerClass();
When I do this, Eclipse says that this line is unacceptable (which I assumed was the case, but it was wishful thinking) since MockInnerClass defaults to protected and thus cannot be used outside its package. Is there a way I can use this class somehow? I did not write the source code, so I am unsure if the lack of a "public" tag on the inner class was intentional or the programmer's mistake.
Thank you in advance.
A bit of an aside, not an actual answer, but I have always put my tests into the same package as the classes being tested. At least, as much as possible, there are a few very rare cases where this is impossible.
Why are you using a different package? Is there a good reason to do so?
Now, back to an answer, if you insist on testing from a separate package, unless MockOuterClass exposes some method to construct (or expose) the MockInnerClass, you are stuck. (I guess you could try using Reflection but that is getting desperate.) However, as several have commented, the author of the class "intended" for the inner class to be hidden, a. la. Kent Beck.
In other words, if you follow Kent Beck, you should be writing tests that target MockOuterClass, NOT MockInnerClass. The inner class is a "non public detail".
If this code wasn't written by you and declares a non-public static class (side-note: it defaults to package-protected, which is very different to protected), chances are the writer intends to hide the class from your use. In short, there is no way to access the class from outside the package, and you probably shouldn't be trying to.

Reflectively instantiating classes in another package, declared with default access in Java

I tried to instantiate a class that was declared with default access, in another package reflectively and received this error:
Class IOTest can not access a member of class com.BinspireD.core.model.DataNodeImpl with modifiers "public".
It this possible (to instantiate a class using reflection in a different package, with package private access)?
How would I properly go about it?
Thanks
The usual solution to these types of problems is as follows:
Think long and hard about what you're trying to do. Is it really necessary?
Chastise yourself with a small flail if you decide that it is.
Cheat. Check out the Javadoc for java.lang.reflect.AccessibleObject.

Java reflecting on method scope variables

Using reflection you can get pretty much everything relating to a class. You can get all the declared methods, fields and classes (and possibly even more), but i couldn't find a way to reflect on a method so i could find out what classes that method might be using.
Essentially i would like to find out all dependencies to other classes that a given class has.
Example:
Given the following code:
import com.yada.yada.yada.SomeClass
public class MyClass
{
public MyClass
{
new SomeClass();
}
}
How can i find out that MyClass is using SomeClass in its constructor?
I was trying to think of a way to get all import statements defined in a class file but i couldn't find anything that way either. But, assuming there's a way to somehow dig up all import statements defined in a class file, how would one find out about classes defined in the same package, which do not require an import statement?
EDIT:
Scenario: The goal is to send the bytecode of this class (MyClass) to another process. This other process then takes in the bytecode and loads the class (MyClass) using class loaders, and so on. The problem is that when i try to create and run an instance of MyClass in the other process it fails because it cannot find a definition for SomeClass.
If SomeClass were a member of MyClass it wouldn't be a problem but since the only reference to it lies in a method, there's no way to get to it via reflection?
I think the closest you can come to getting all of a class's dependencies is by hooking into the class loader mechanism and recording what classes get loaded when the class you're examining is instantiated and its methods are called. Of yourse, you'd transitively also get all the classes that it indirectly depends on, but depending on what you want to do with the information, that may be what you actually need.
But it's impossible to do for all cases (just imagine a method that uses Class.forName() to ask for a random class name every time it's called).
how would one find out about classes defined in the same package
That's actually impossible to do in general, since the class loader concept really only allows asking for a fully qualified class name, and either getting that class or a ClassNotFoundException. Classes can be loaded from a webserver (in the case of applets) or generated on the fly, so you cannot know whether a specific class exists except by asking for it.
You can't (unless you decompile the bytecode). A local variable is not tied to any class instance, and it does not even exist for most of the lifetime of the class or its instances, so you can't access it via reflection.
What are you trying to achieve? Maybe if you tell us about your actual problem, rather than a perceived solution, we are better able to help.
Reflection does not help you here. The only way I can think of that you can achieve this is through a byte code tool like asm.
Create a ClassVisitor that gathers dependencies from
Class declarations
Annotations
Local variable declarations
Field declarations
Method declarations
Method invocations
(have I forgotten anything?)

Java: Subclass access without package access

Fairly new to Java, but I'm wondering why package access is considered "more restrictive" than subclass access. That is, every access modifier which provides subclasses with access to a member also provides the whole package with access, and there are modifiers whic provide package access but not subclass access.
Isn't this totally backwards? Let's say I have a class ControlledInstantiation in some package. If I have another class AlsoControlledInstantiation extends ControlledInstantiation, I am unable to call the constructor of ControlledInstantiation unless I set it to protected or public. And if I set it to protected, now any other class in the package can instantiate it as often as it likes. So something which is obliged to be substitutable for its superclass (and, syntactically, is) gets the same or less access to the superclass than something which serves a distinct but related function. It's like telling your child he can't play with your wallet because you wouldn't let your neighbours do it and then letting your neighbours sleep in your house because your kid does.
So I guess I'm asking, what motivated this decision, and how can I get around it?
It may seem backwards at first, but the idea is that a Java package should contain a set of comparatively cohesive classes which are semantically related, and this is reflected in the default package modifier. Then the logic is that if you want to go one step further and allow subclasses from any package to view your members, you can declare them protected. Does it make sense to you that subclasses from foreign packages should be less trusted than any class (whether a subclass or not) from your own package?
Java did in fact once have a private protected modifier which would achieve what you're after, but it was removed, I imagine, because it confused people. I'm not really sure how you could achieve this without relegating each class/subclass pair to its own package. But that's a messy solution which goes against Java's principles and it wouldn't work for inheritance hierarchies of more than two classes anyway.
You are right, this fact is a little bit confusing.
Here are the workarounds I can suggest.
Your example with protected constructor is more relevant for methods. In some cases you can avoid access to protected constructor by package member that are not the subclasses of current class if you mark class as abstract.
If you really wish to avoid access to protected method by package members you can solve this problem at least at runtime using Throwable.getStacktrace():
if(!getClass().isAssignableFrom(
Class.forName(new Throwable().getStackTrace()[1].getClassName()))) {
throw new IllegalAccessException(
"This method can be accessed by subclass only");
}
You can seal a package. See the JAR File Specification.

Categories

Resources