Javagenerics从类创建数组
我有一个层次结构,其中Square,Triangle和Circle都从Shape扩展。 我有一个工作方法:
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(); }
现在我想使这个方法通用,以便它可以接受任何形状。 我希望能够将其称为someMethod(Triangle.class,new File("File_with_triangles")
或someMethod(Circle.class, new File("File_with_circles")
。我正在尝试这样:
public void someMethod(Class type, File shapeFile) { ThirdPartyClass foo = new ThirdPartyClass(); #### What goes here??? #### for (Shape shape: shapes) shape.draw(); }
应该在####那里有什么? #### ???
假设ThirdPartClass.someMajicMethod有这样的签名:
public T someMajicMethod(Class class1, File file);
然后你应该能够做这样的事情:
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(); }
所以如果你调用someMethod(Triangle.class, file)
,那么在调用someMajicMethod
, arrayType
将是Triangle[].class
someMajicMethod
。
虽然您可能会发现让someMethod将数组类型作为参数而不是元素类型更简单,因此您可以避免该步骤。
也许Array.newInstance(..)对你很感兴趣
Shape[] shapes = foo.someMajicMethod(type, file);
如果foo
是第三方类,我假设你不控制它的API。 我假设它有适当的方法签名来处理我写过的行,但是如果没有关于该类的更多信息,我无法确定。
如果这不起作用,问题是什么?