這是一個關於我不確定如何在Java中解決的問題。我想根據三種類型的數據(URI,字符串或文字)製作三重語句,每種類型的編碼方式都不相同。我已經編寫了接受這些類型的編碼方法。在Java中接受不同類型的參數
public static String makeStatement(URI subject, URI predicate, String object) {
return " " + encode(subject) + " " + encode(predicate) + " " + encode(object) + ".\n";
}
public static String makeStatement(String subject, URI predicate, String object) {
return " " + encode(subject) + " " + encode(predicate) + " " + encode(object) + ".\n";
}
public static String makeStatement(URI subject, URI predicate, Literal object) {
return " " + encode(subject) + " " + encode(predicate) + " " + encode(object) + ".\n";
}
private static String encode(String binding) {
return "?" + binding;
}
private static String encode(URI uri) {
return "<" + uri.stringValue() + ">";
}
private static String encode(Literal literal) {
return "\"" + literal.stringValue() + "\"" + literal.getDatatype();
}
但我能接受這些類型的,這需要9個makeStatement功能,基本上做同樣的事情的任意組合,這似乎像一個壞主意,特別是因爲有可能我想補充另一稍後鍵入。
通常我會回答這樣一個問題,建議創建一個superClass,但我不能編輯String,URI和Literal。另一種選擇是定義
public static String makeStatement(Object subject, Object predicate, Object object) {
String encodedSubject = "", encodedPredicate = "", encodedObject = "";
if (subject.getClass().equals(URI.class)) {
encodedSubject = encode((URI) subject);
}
return " " + encode(encodedSubject) + " " + encode(encodedPredicate) + " " + encode(encodedObject) + ".\n";
}
然後檢查類各的說法,但我認爲這不是很優雅。 另一個建議是定義諸如makeStatement(URI subjectURI,String subjectString,Literal subjectLiteral,URI predicateURI ..等)之類的東西,然後檢查哪些參數爲null並從那裏開始,但這意味着當我打電話時輸入很多空值功能。 第三個選項是https://stackoverflow.com/a/12436592/1014666,但這又需要在調用makeStatement函數時進行一些額外的輸入。
有什麼建議嗎?
一個同事面對類似的問題,他回來了,他寫了一個Python腳本,將所有9個組合寫成.java文件中的文本 – mbatchkarov
不錯,但不是很優雅:) – Rhand
編寫一個通用方法接受所有對象作爲對象並在裏面做檢查的實例,並根據需要執行操作。它可能會給你另一種觀點。 – Arung