I have a Java class with a nested protected class in it. In a method of another class (and in another package) I have to make a list of such nested protected type.
Is there a way to do this in Java?
// SomeClass.java
package stuff;
public class SomeClass {
protected class Nested {
int x;
public Nested setX(int arg) {
x = x;
return this;
}
public int getX() {
return x;
}
}
public Nested make(int x) {
return new Nested().setX(x);
}
}
// MyClass.java
package project;
import java.util.List;
import java.util.ArrayList;
import stuff.SomeClass;
public class MyClass {
public SomeClass instance;
// I don't know what I should insert ...
public List< /* ... here... */ ?> method() {
var list = new ArrayList< /* ... and here... */ >();
list.add(instance.make(1));
list.add(instance.make(2));
return list; // ... to return an ArrayList<SomeClass.Nested>
}
}
Even some reflection magic would be ok for me
PS. I whuld not modify SomeClass
CodePudding user response:
You cannot, as Nested
is not accessible outside of SomeClass
. You can either make Nested
public (or package-private if both SomeClass
and MyClass
are in the same package), or move MyClass
inside of SomeClass
.
CodePudding user response:
One solution is to create a public interface which Nested
implements. Then you can refer to that interface type List<MyInterface>
, for example. And make()
returns the interface type, instead of Nested
. This is the pattern used by many classes in the standard Java API.
CodePudding user response:
First of all you should know, that ther're static
and not static
inner classes.
Only one differenct: static
class does not have a reference to it's parent class (but non static
does). So it is not possible to create non static
inner class without it's parent.
In case you want to have a list (e.g. Tree
and Tree.Node
), looks like you should create a static inner class
.
Anyway, you can create a list of inner classes like List<[ParentClass].[InnerClass]>
(you can have many .
like List<A.B.C.D.E>
).
public class MyClass {
public SomeClass instance;
public List<SomeClass.Nested> method() {
List<SomeClass.Nested> list = new ArrayList<>();
list.add(instance.make(1));
list.add(instance.make(2));
return list;
}
}