2013-08-05 4 views
0

그래서, 안드로이드 sqlite에 대한 작은 라이브러리를 만들려고 해요, 그리고 대부분의 기본 기능을 가지고 있지만 문제가있는 특정 결과를 반환하는 것입니다. 수업. 나는 일반 하위 클래스로 캐스팅

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(); 
    } 
} 

있어하지만 row.getClass(). 대한 getName 로그온을 시도 할 때마다(), 항상 다시 행,하지 RowClass로 제공하고, 대신 RowClass의, 행과 같은 역할을합니다. RowClass에 행을 캐스트하려면 어떻게해야합니까?

편집 : 표

public class SourcesTable<Rowclass extends Row> extends Table<Row> 
{ 
    public String getName() 
    { return "sources"; } 

    public String[] getAllColumns() 
    { 
     String[] columns = { "name" }; 
     return columns; 
    } 
} 

에서 확장 그리고

Tables sourcesTable = new SourcesTable<SourcesRow>(); 
List<SourcesRow> list = sourcesTable.fetchAll(); 

public class SourcesRow extends Row 
{ 
    public String toString() 
    { return this.data.get("name"); } 
} 

그리고

public class Row 
{ 
    public String toString() 
    { return ""; } 
} 
로 인스턴스화 무엇

죄송합니다. PHP를 사용하여 자바를 배우고 있습니다. 잘못된 방식으로 사용하려고합니다. 엄격한 유형 변환에 익숙하지 않습니다.

+2

RowClass가 행을 확장하는 경우 어떻게 Row를 RowClass로 변환 할 수 있습니까? –

+0

호출 코드를 보여줄 수 있습니까? (즉, 표를 확장하는 클래스 및 그 인스턴스화). 우리는 당신의 오해를 더 잘 설명 할 수있을 것입니다. – torquestomp

+0

귀하의 질문은 제게 익숙하지 않거나 제네릭이 아닌 것으로 보였기 때문에 귀하의 질문에 불충분하게 말하거나 이해할 수 없습니다. "하위 클래스로 제네릭을 캐스팅"한다는 것은 정확히 무엇을 의미합니까? 왜냐하면 RowClass는 자체적이지 않기 때문입니다. 테이블과 목록은 ... 더 많은 코드가 필요합니다. –

답변

2

이것은 관련 코드입니다

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 서브 클래스를 적절하게 구성합니다.

희망이 있습니다.

+1

고맙습니다. 당신은 내가하려는 일에 완전히 옳다. 두 번째 대답은 훨씬 더 편리하고 더 많은 목적에 부합한다. 혼란스럽게해서 죄송합니다. PHP에서 나온 후 Android 앱을 만드는 법을 배우려고합니다. 조금 혼란 스럽습니다. –

+1

대단합니다. 위의 대답을 편집하여 Table 하위 클래스 (위의 SpecialTable 및 CustomTable 예제)의 사용 예를 추가했습니다. 행운을 빕니다! 너는 그것을 알아낼 것이다. Java는 매우 깨끗한 언어이며 배우기 쉽습니다. –

관련 문제