簡體   English   中英

如何在子類上下文中執行從超類繼承的方法?

[英]How to execute methods inherited from super-class in the subclass context?

我正在實現一個類似於JPA的過程:代表表的所有類都必須子類化一個DBTable抽象類,該類包含一個HashMap,它將列名(字符串)鏈接到我從調用getClass().getDeclaredFields()獲得的java.lang.reflect.Field getClass().getDeclaredFields()在超類構造函數中,從子類構造函數調用。 這正在工作(我從子類中獲取了想要的成員)。

我想從ResultSet動態設置子類的這些成員,該方法將在最初在超類中作為助手實現的方法中調用Field.set(this, ResultSet.getXXX(column)) ,但我得到了java.lang.IllegalAccessException: Class DBTable can not access a member of class MyTable with modifiers "protected"

因此,事實證明該方法是在超類上下文(抽象類!)中執行的:如果我將方法復制/粘貼到子類中,則可以正常工作。

這是一個片段:

public abstract class DBTable {
    public DBTable() {
        hm = new HashMap<String,Field>();
        for (Field f : getClass().getDeclaredFields()) {
            hm.put(f.getAnnotation(Annot.class).value(), f); // 'annot' gives the column name
        }
    }

    protected boolean setFieldClass(Field f, ResultSet rs, int iCol) {
        Class<?> type = f.getType();
        if (type == String.class) {
            f.set(this, rs.getString(iCol)); // IllegalAccessException
        }
    }

    public boolean read(ResultSet rs) {
        ResultSetMetaData meta = rs.getMetaData();
        for (int i = 1; i < meta.getColumnCount(); i++) {
            Field f = hm.get(meta.getColumnName(i));
            setFieldClass(f, rs, i); // IllegalAccessException
        }
    }

    public abstract someAbstractOtherMethod();
}

public class MyTable extends DBTable {

    @Annot("DataCol") // Set the column name to "DataCol"
    protected String dataStr;

    public MyTable() {
        super();
    }

    // 'dataStr' getter/setter
    // 'someAbstractOtherMethod' implementation
}

public static void main(String[] args) {
    MyTable mt = new MyTable();
    ResultSet rs = ...; // Execute SELECT query returning a single row with a "DataCol" column containing a varchar(32)
    mt.read(rs); // IllegalAccessException
}

MyTable對象上調用的read方法是從DBTable類繼承的,而DBTable類又調用了setFieldClass方法,該方法引發錯誤。 如果我將setFieldClass方法從DBTable復制/粘貼到MyTable則可以正常工作,也可以將dataStr成員更改為public。

我可以調用setter而不是直接設置成員值,但要避免這樣做(我不確定子類是否會實現它,也不會都給出相同的名稱)。

感謝您與我分享您的見解! :)

在調用Field.set之前調用Field.set Field.setAccessible(true)

正常,無法構造抽象類。 那就不可能構造它。 當編寫public class MyTable extends DBTable ,編譯器將執行繼承的方法。 不使用測試 我認為這可能有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM