Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

Can you create a Java array of an anonymous class?

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?

question from:https://stackoverflow.com/questions/65913448/can-you-create-a-java-array-of-an-anonymous-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...