我有一个层次结构,其中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<? extends Shape> type, File shapeFile) {
ThirdPartyClass foo = new ThirdPartyClass();
#### What goes here??? ####
for (Shape shape: shapes)
shape.draw();
}
####应该有什么?这里有什么? #### ???
答案 0 :(得分:4)
或许你感兴趣Array.newInstance(..)
答案 1 :(得分:4)
假设ThirdPartClass.someMajicMethod有这样的签名:
public <T> T someMajicMethod(Class<T> 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)
,那么arrayType
将Triangle[].class
调用someMajicMethod
。
虽然你可能会发现让someMethod将数组类型作为参数而不是元素类型更简单,所以你可以避免这一步。
答案 2 :(得分:3)
Shape[] shapes = foo.someMajicMethod(type, file);
如果foo
是第三方类,我认为您无法控制它的API。我假设它有适当的方法签名来处理我写过的行,但是如果没有关于该类的更多信息,我无法确定。
如果这不起作用,问题是什么?