Java Generics Creating an Array from a Class

I have a hierarchy where Square, Triangle and Circle all extend from Shape. I have a working method:

public void someMethod() {
   File file = new File("File_with_squares");
   ThirdPartyClass foo = new ThirdPartyClass();
   Square[] squares = foo.someMajicMethod(Square[].class,file);
   for (Square square: squares) 
      square.draw();

}

Now I want to make this method general so that it can take any form. I want to be able to call him someMethod(Triangle.class,new File("File_with_triangles")or someMethod(Circle.class, new File("File_with_circles"). I try like this:

public void someMethod(Class<? extends Shape> type, File shapeFile) {
   ThirdPartyClass foo = new ThirdPartyClass();
   #### What goes here??? ####
   for (Shape shape: shapes)
       shape.draw();
}

What should be there in #### What is happening here ??? #### ???

+5
source share
3 answers

Assuming ThirdPartClass.someMajicMethod has a signature something like this:

public <T> T someMajicMethod(Class<T> class1, File file);

Then you can do something like this:

public void someMethod(Class<? extends Shape> type, File shapeFile) {
    ThirdPartyClass foo = new ThirdPartyClass();

    @SuppressWarnings("unchecked")
    Class<? extends Shape[]> arrayType = 
        (Class<? extends Shape[]>) Array.newInstance(type, 0).getClass();
    assert Shape[].class.isAssignableFrom(arrayType);

    Shape[] shapes = foo.someMajicMethod(arrayType, shapeFile);

    for (Shape shape: shapes)
        shape.draw();
}

So, if you call someMethod(Triangle.class, file), it arrayTypewill be Triangle[].classin the call someMajicMethod.

, someMethod , , .

+3
Shape[] shapes = foo.someMajicMethod(type, file);

foo , , API. , , , , .

, ?

+3

All Articles