[英]Creating an array of generics in java in the method, without a class object
[英]Java Generics Creating Array from Class
我有一個層次結構,其中 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();
}
#### 應該有什么這里有什么??? ####???
也許Array.newInstance(..)你感興趣
假設 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();
}
因此,如果您在調用 someMajicMethod 時調用someMethod(Triangle.class, file)
,則arrayType
將為Triangle[].class
someMajicMethod
。
盡管您可能會發現讓 someMethod 將數組類型作為參數而不是元素類型更簡單,因此您可以避免該步驟。
Shape[] shapes = foo.someMajicMethod(type, file);
如果foo
是第三方 class,我假設你不控制它的 API。 我認為它具有適當的方法簽名來處理我編寫的行,但是如果沒有關於 class 的更多信息,我無法確定。
如果這不起作用,有什么問題?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.