I am wondering if it is possible to create an array of a Java anonymous class. For example, I try this code:
final var anonArray = new Object() {
public String foo = "bar";
}[4];
However that gives an error: error: array required, but <anonymous Object> found
. Is this possible?
Remember that new Object() {...}
gives you a value not a type.
So, here is how you could create an array of instances of anonymous classes:
final Object[] anonArray = new Object[]{
new Object(){
public String foo = "bar1";
},
new Object(){
public String foo = "bar2";
},
new Object(){
public String foo = "bar3";
},
new Object(){
public String foo = "bar4";
}
};
Or if you want an array with the same anonymous class instance 4 times:
final Object anonInstance = new Object(){
public String foo = "bar1";
};
final Object[] anonArray = new Object[]{
anonInstance, anonInstance, anonInstance, anonInstance
};
Or if you want 4 distinct instances of the same anonymous class:
final Object[] anonArray = new Object[4];
for (int i = 0; i < anonArray.length; i++) {
// Just to show we can do this ....
final String bar = "bar" + 1;
anonArray[i] = new Object(){
public String foo = bar; // Look!
};
}
Note that in all of the above the array type is Object[]
not "array of the anonymous subclass of Object
". It is difficult to conceive that this would matter, but if it did matter you would need to resort to reflection to create the array class. (See @ernest_k's answer.)
Or just declare an array of an appropriate custom class or interface, and create anon subclasses from that class / interface. Anonymous subclasses of Object
are not exactly practical ...