Reputation: 394
I have class A, class B and class C.
class B is an inner class of class A. As shown below:
public class A {
public class B {
String day;
HashMap<String, ArrayList<Date>> locationTimes;
public B() {
locationTimes = new HashMap<String, ArrayList<Date>>();}
}
**B fieldB;**
.....
}
Using dependency injection(may not be relevant to the problem), I inject the object of class A into class C.
I am now trying to access the fields (String day, HashMap locationTimes) within class B, from a different object of class C. But I am unable to do so.
Any help is appreciated.
Upvotes: 1
Views: 1454
Reputation: 813
You have to create an instance of B like:
public class A {
private B b;
public B getB() {
return b;
}
public static class B {
String day;
HashMap<String, ArrayList<Date>> locationTimes;
public B() {
locationTimes = new HashMap<String, ArrayList<Date>>();
day = "Monday"
}
public String getDay() {
return day;
}
}
}
Then you can access the attrbutes from B like this:
public class C {
private A a;
public void doSomething() {
a.getB().getDay();
}
}
Edit: You need your class B to either be private
or public static
.
Upvotes: 3
Reputation: 89
I am guessing you do not have an instance of your inner class? In that case you should make that yourself.
Within the outer class you can create a new instance of the inner class
public class Outer {
Inner myInner;
public Outer(){
myInner = new Inner();
}
}
And if you need to access the inner class directly from the outside, you could have a getter method for that instance.
This answer is different from Dimi's in that (s)he has changed changed your inner class to a nested static class which is different from the original question. (Also, it is incomplete, and not the intended way to use static nested classes)
Upvotes: 0
Reputation: 26
Yeah, you need to have an instance of B somewhere.
In your case the container is creating an instance of A like:
public class C {
@Inject
A a;
void someMethod() {
a.doit();
A.B b = new A.B();
b.doitToo(); // will work
}
}
Upvotes: 0