我有幾張表,我有SELECT *
'd到XML文件中。我們稱它們爲A,B和C映射到的A,B和C表。我希望有一個泛型類,而不是獨立的AXMLDao,BXMLDao和CXMLDao。創建擴展SAXParser默認處理程序的通用類
A,B和C具有映射到其各自的A,B和C表的成員變量。我在每個A,B,C類中都有public static Map<String, Method> getSetMethodMap()
,它使用反射API在相應類中返回數據庫字段名稱映射到mutator方法。
我已經做了一個當前的實施,但它失敗的兩個罪名:1)它充滿了警告,因爲我沒有正確地做,2)我不知道我將如何能夠通過訪問getSetMethodMap()
通過類型參數。
如果我使用非靜態方法public Map<String,Method> getMethodMap();
創建一個名爲ReflectionType的接口,並將以下實現更改爲<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);
}
我很明顯沒有正確掌握泛型/類型參數化。
如何清理?
請問您可以發佈警告(行和消息)? – ssantos