Access private inner class, through a public outer class - from another class - java

I am completely stuck on this and have been playing around with it for a while. I have a class "launcher", from which I want to access an instance of a private inner class "PropertyInstance", through the outer class "PropertyManager".
So, in my launcher I would like to write:
PropertyManager pm = new PropertyManager();
PropertyInstance pi = pm.getInstance("brickbreaker.properties");
In my PropertyManager class I have written the following code:
public PropertyInstance getInstance(String location)
{
PropertyInstance pi = null;
if(!propertyList.contains(location))
{
System.out.println("it does not contain it yet, so we will create it");
pi = new PropertyInstance(location);
propertyList.add(pi);
}
return pi;
}
And inside this class, I have the following inner class:
private class PropertyInstance
{
}
Which is irrelevant apart from the private modifier.
The problem is that I can not access the PropertyInstance class from my Launcher due to it being private, and I do not seem able to find a workaround so really any help is appreciated. If it can even be done.
EDIT: It seems to be unclear that I'm looking for a workaround whilst keeping the inner class private, sorry for the confusion! :)

Make an interface that defines the public access you want to your private class, make your private class implement it, and return it as that.

The workaround is to make it public.

Related

Private static inner class - Powermock

I want to mock private static inner class using Powermock (based on EasyMock). This does not come from production code, it's just a question whether something is possible. I am pretty sure this is bad design, but it's something I'm trying for science.
Let's say we have a class with static private inner class:
public class Final {
private static class Inner {
private final int method () { return 5; }
}
public int callInnerClassMethod () {
return new Inner().method();
}
}
I would like to mock the Inner class and its method.
I have come out with the code as follows:
Class<?> innerType = Whitebox.getInnerClassType(Final.class, "Inner");
Object innerTypeMock = PowerMock.createMock(innerType);
PowerMock.expectNew(innerType).andReturn(innerType);
PowerMock.expectPrivate(innerType, "method").andReturn(42);
PowerMock.replay(innerTypeMock);
new Final().callInnerClassMethod();
In the code: we get the type of Inner.class and mock it, when a user creates new object of type Inner we say that we return our instance, and when someone calls its method we provide our implementation for it.
Generally, I am learning about mocking and one can be sure this code proves I don't know what I'm doing. The code does not even compile and I get the following error on the line PowerMock.expectNew(innerType).andReturn(innerType):
andReturn (capture) in IExpectationSetters cannot be applied to
(java.lang.Object)
 Is the mocking of private static inner class even possible? I have not found a definitive code example on SO.
I have managed to get around the compile error by using bare Class innerType = ... instead of Class<?> innerType = ... in my code. It feels wrong, but works. I'd grateful if someone explained the difference and how to make it work in the original example. There were also some places where I mixed innerType and innerTypeMock. The full, working test code looks as follows:
Class innerType = Whitebox.getInnerClassType(Final.class, "Inner");
Object innerTypeMock = PowerMock.createMock(innerType);
PowerMock.expectNew(innerType).andReturn(innerTypeMock);
PowerMock.expectPrivate(innerTypeMock, "method").andReturn(42);
PowerMock.replayAll();
System.out.println(""+new Final().callInnerClassMethod());

Setting private field in abstract super class using mockito

I am having a abstract super class TP and which have a concrete sub class ETP. This is my code:
abstract class TP {
private Configuration app;
protected MC bMC() {
}
}
and sub class ETP code is:
public class ETP extends TP {
private Configuration app;
public MC pT() {
bMC();
}
}
I am writing test case for ETP which is ETPTest which looks like this
public class ETPTest {
#Before
public void setUp() throws Exception {
// as TP is abstract i am initializing with ETP
TP = new ETP();
// some initialization
}
Whitebox.setInternalState(TP, app);
}
but app is getting passed as null in TP and getting NPE in TP.
any ideas or suggestions?
app is a private variable defined in both TP and ETP; and I am trying to set internal state for app which is in TP.
Your difficulties to such things can be seen as a symptom.
You can decide that the cure is to spent hours until you get the mocking parts to circumvent around that problem.
Whereas the other option is: understand that the given design is deficient:
sub classes should absolutely not care about private fields in super classes. The whole point of private is to make things an "implementation detail" that no other class should know or care about
Worse: by putting up a second private field with the same name, you just added to that confusion. Those will be to different private fields; there is no "overriding" or "polymorphism" here.
In the end, you probably do not understand how to properly design a solution that uses inheritance and abstract base classes. You should thus step back, and think for example, if a solution like this helps:
public abstract class Base {
protected abstract Configuration getConfiguration();
public final void doSomething() {
... calls getConfiguration() to do its jobs
}
}
and then:
public abstract class Subclass extends Base {
protected Configuration getConfiguration() {
return whatever
As a rule of thumb: clean, straight-forward, non-surprising designs can most often be unit tested simply by using dependency injection and one mock here and another one there. As soon as you have to look into all these complex "solutions"; such as mocking super-class methods/fields; or mocking static methods, ... you are already suffering from a bad design; and instead of fixing that problem; you try to work around it.
That will not help you in the long run. Because the real problem is the "smelly" design in your production code.

Java: how do I access the variables of another class

I have a class GameScreen which has an instance of a class Sprites (I have named the instance gameSprites). In Sprites there is an instance of a third class, which I have named enemies.
My question is, can I access a variable in enemies from GameScreen?
Can I type gameSprites.enemies.variableName?
And can I continue that for more than two different classes?
If Your Variable is Private you need to have Public method to access that Variable .
Suppose I have This Dummy Enemies Class of Yours
package com;
public class Enemies {
private final String name="HELLO";
public final String names="This is public Variable";
public static String name2="HELLO THIS IS STATIC";
public Enemies(){};
public String getName(){
return name;
}
}
and here in Sprites Class like your requirement i created Enemies instance
package com;
public class Sprites {
public Sprites(){};
Enemies enemies = new Enemies();
}
This is Dummy GameScreen Class
package com;
public class GameScreen {
public static void main(String...strings){
Sprites gameSprites = new Sprites();
System.out.println(gameSprites.enemies.names);
String name=gameSprites.enemies.name2;// This is Highly Discouraged Approach
System.out.println(name);
System.out.println(gameSprites.enemies.getName());
}
}
and the Output When You Run This Code.
This is public Variable
HELLO THIS IS STATIC
HELLO
So What you are trying to achieve can be done for public and Static variable(This one is not encouraged to do) . For private you need to have a Public Method to access that Variable.
In Java world, its not really recommended. You're able to access via objectName.memberName because your member attribute is a public one. As a convention, we usually keep members private and have getters and setter through which we access the values.
And coming back your question, you can access that way to any level given that each of the members are declared public. Say, gameSprites.enemies.enemy1.enemy1Army.solder1 is also possible if enemies is public in gameSprites class, enemy1 is public in enemies class and so on.
This is really very basic things of any OOP language. In my opinion, you should spend some times on study those basic things, otherwise there is a good chance that you will stuck further when you proceed from this problem. However, here is an example to how to access variable of other class from another class.
Accessing a variable from another class
It might be accessible if there is public property of class "enemies". But you are not doing it in a right way. You should make these properties private, then create public methods(getter/setter) to access the properties of those objects.

Java - Declare Class Once Use Anywhere

Very simple problem but im not understanding static correctly.
I have java file which holds my main and its call testMain.
With my testMain it makes many classes with use other classes.
E.g. testMain>>GUI and testMain>>model and testMain>>controller
Now i have a class called generatorTester which i would like to declare once like:
public static utils.generatorTester randomGen = new utils.generatorTester ();
(utils is my custom package for my common classes)
Why does the above line not aloud me to do the following
classNameOfMainFunction.randomGen
Im i programming wrong here? Is this even possbile.
I bassicly want to make the class globably and use it any where.
A public static field of a public class can be used anywhere, you just need to use the right syntax to access it.
If you declare:
package foo;
public class Global {
public static Some thing;
}
And do
import foo.Global;
you can access the field with
Global.thing
Alternatively, you can do
import static foo.Global.thing;
and access it with
thing
About the best you can get is this:
public abstract class GloballyUsed {
public static int method() { return 4;
/* determined by fair
* dice roll, guaranteed to be random */
}
and:
GloballyUsed.method();
to call elsewhere.
Note per comment (I just learned this) since Java 5 you can import just a specific method name as:
import static {package}.GloballyUsed.method;
Note I added the keyword abstract, this is to further convince you that you never actually instantiate GloballyUsed. It has no instances. You probably have some reading to do on what static means.

jMockit's access to a private class

I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!
The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");
As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.
Change the scope of the inner class to default then make sure that the test is in the same package.
There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.

Categories