이것은 관련 코드입니다
abstract public class Table<RowClass extends Row>{
public List<RowClass> fetchAll() {
//Fetch the stuff here
//In the while class to add each row to the array
RowClass row = (RowClass) new Row();
}
}
당신이 요구하는 것은 RowClass
의 새로운 인스턴스를 생성하는 방법을 것 같습니다 : 코드의 당신은 사실) : 불필요한에 게시 됨. 당신은 할 수 없습니다. Java는 RowClass 유형에 대한 정보를 제공하지 않습니다. 형식 지움으로 인해 일반 매개 변수로 전달 된 형식에 대한 정보는 런타임에 존재하지 않습니다. 제네릭 매개 변수 유형의 객체를 인스턴스화하려면 다른 방법으로 클래스를 제공해야합니다. 예를 들어 (예외 처리는 명확성을 위해 왼쪽으로) :
abstract public class Table<RowClass extends Row>{
private final Class<RowClass> rowClass; // holds the Class of each row
public Table (Class<RowClass> rowClass) {
this.rowClass = rowClass;
}
public List<RowClass> fetchAll() {
//Fetch the stuff here
//In the while class to add each row to the array
RowClass row = rowClass.newInstance();
}
}
는 그런 다음, 서브 클래스가 슈퍼 생성자에 자신의 행의 클래스를 전달해야 할 것입니다 귀하의 경우, 그래서 표, 추상적이다 (표 생성자에 Whatever.class 전달), 예 :
// assume: SpecialRow and MyCustomRow are concrete classes extending Row
// and defined elsewhere.
// scenario 1 - subclass knows row type
public class SpecialTable extends Table<SpecialRow> {
public SpecialTable() {
super(SpecialRow.class);
}
}
// scenario 2 - subclass still lets user specify row type
public class CustomTable <R extends Row> extends Table<R> {
public CustomTable (Class<R> rowClass) {
super(rowClass);
}
}
// usage:
SpecialTable special = new SpecialTable();
CustomTable<MyCustomRow> custom = new CustomTable<MyCustomRow>(MyCustomRow.class);
또한 예를 들어, fetchAll에 클래스를 전달할 수 : 통과도) 작동 (일반 toArray가 (어떻게 정신에는 변함) 객체를
public List<RowClass> fetchAll(Class<RowClass> rowClass) {
//Fetch the stuff here
//In the while class to add each row to the array
RowClass row = rowClass.newInstance();
}
를 또는, 사장님 E :
public List<RowClass> fetchAll(RowClass refObject) {
//Fetch the stuff here
//In the while class to add each row to the array
RowClass row = refObject.getClass().newInstance();
}
자세한 내용은 다음을
편집 : 대안 설계 방식은, 여기가 있으면 내 추측 일에 대해 당신 옳은 일을하려고 노력하고있다.
테이블이 추상적이기 때문에 서브 클래스에 고유 한 특정 행 유형이있는 테이블 서브 클래스를 만들려고한다는 의미가 있습니다. 이 경우, 위의 첫 번째 옵션 (클래스 생성자를 슈퍼 생성자로 전달)이 가장 적절합니다.
abstract public class Table { // no generics necessary
// subclasses must override this
abstract protected Row newRow();
// the base class can use newRow() to let the subclass determine the type
public List<Row> fetchAll() {
// in the while loop to add each row to the array:
Row row = newRow();
}
}
이 방법의 주요 있습니다 그러나, 대신에이 모든 일을, 당신은 서브 클래스가 자신의 알려진 행 클래스를 인스턴스화시키는, 그리고 예를 들어, 기본이 할 수있는 추상적 인 방법을 제공하는 것을 고려하실 수 있습니다 let의 장점 특정 Row 서브 클래스에 대해 알고있는 Table 서브 클래스는 Row 서브 클래스를 적절하게 구성합니다.
희망이 있습니다.
RowClass가 행을 확장하는 경우 어떻게 Row를 RowClass로 변환 할 수 있습니까? –
호출 코드를 보여줄 수 있습니까? (즉, 표를 확장하는 클래스 및 그 인스턴스화). 우리는 당신의 오해를 더 잘 설명 할 수있을 것입니다. – torquestomp
귀하의 질문은 제게 익숙하지 않거나 제네릭이 아닌 것으로 보였기 때문에 귀하의 질문에 불충분하게 말하거나 이해할 수 없습니다. "하위 클래스로 제네릭을 캐스팅"한다는 것은 정확히 무엇을 의미합니까? 왜냐하면 RowClass는 자체적이지 않기 때문입니다. 테이블과 목록은 ... 더 많은 코드가 필요합니다. –