我有一个层次结构,其中正方形、三角形和圆形都从形状延伸。我有一个工作方法:
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")
or 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();
}
#### 应该有什么 这里有什么??? #### ???
假设 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)
, then arrayType
将Triangle[].class
在通话中someMajicMethod
.
尽管您可能会发现让 someMethod 将数组类型而不是元素类型作为参数更简单,因此您可以避免该步骤。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)