SELECT *
XML ファイルに変換したテーブルがいくつかあります。それらを、Java クラス A、B、および C にマップするテーブル A、B、および C と呼びましょう。個別の AXMLDao、BXMLDao、および CXMLDao を作成する代わりに、1 つのジェネリック クラスが必要です。
A、B、および C には、それぞれの A、B、および C テーブルにマップされるメンバー変数があります。リフレクション API を使用してpublic static Map<String, Method> getSetMethodMap()
、それぞれのクラスのミューテーター メソッドにデータベース フィールド名のマッピングを返す各 A、B、C クラスがあります。
getSetMethodMap()
現在の実装を作成しましたが、次の 2 つの点で失敗します。1) 正しく実行していないため、警告がいっぱいです。2)型パラメーターを介してにアクセスする方法がわかりません。;
非静的メソッドを使用して ReflectionType というインターフェイスを作成しpublic Map<String,Method> getMethodMap();
、次の実装をに変更すると<T extends ReflectionType>
、methodMap を設定できますが、これは間違っていると感じます。
これが私の現在の実装です。
public class GenericXMLDao<T> extends DefaultHandler {
List<T> rows;
String xmlFileName;
Map<String, Method> methodMap; // This is for Reflection API
T tempRow;
String tempValue;
public static Map<Class, String> getXMLFileMap() {
Map<Class, String> map = new HashMap<Class, String>();
map.put("A.class", "C:\\A.xml");
....
return map;
}
public String fetchXMLFileName(Class c) {
Map<Class,String> map = GenericXMLDao.getXMLFileMap();
// Try Catch Throw exception if Class is not in map, but essentially:
return map.get(c);
}
public List<T> getAllRows(Class c) {
rows = new ArrayList<T>();
xmlFileName = fetchXMLFileName(c);
parseDocument();
return rows;
}
private void parseDocument() {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
parser.parse(xmlFileName, this);
// catch ....
}
@Override
public void startElement(String s, String s1, String elementName, Attributes attributes)
throws SAXException {
if (elementName.equalsIgnoreCase("DATA_RECORD")) {
try {
tempRow = (T) tempRow.getClass().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
...
}
}
}
}
@Override
public void endElement(String s, String s1, String element) throws SAXException {
if (element.equals("DATA_RECORD")) {
rows.add(tempRow);
}
for (Entry<String,Method> entry : methodMap.entrySet()) {
// Try ... catch reflection api
if (element.equalsIgnoreCase(entry.getKey))) {
entry.getValue().invoke(tempRow, tempValue);
}
}
}
@Override
public void characters(char[] ac, int i, int j) throws SAXException {
tempValue = new String(ac, i, j);
}
ジェネリック/タイプのパラメーター化を適切に把握していないことは明らかです。
これはどのようにクリーンアップできますか?