這是不可能投下孩子小時候也不是可以投一個孩子給家長,然後回到父母。於是我寫了一個通用翻譯器,將BankInstruction的一個子類的所有數據複製到另一個。
/**
* Convert a BankInstruction Child class to another bank instruction child class
*
* @param incoming
* The incoming child class with data
* @param clazz
* The class we want to convert to and populate
* @return
* The class we requested with all the populated data
*/
public static <I extends BankInstruction, O extends BankInstruction> O convertBankInstructionModel(final I incoming,
final Class<O> clazz) {
// Create return data object
O outgoing = null;
// Attempt to instantiate the object request
try {
outgoing = clazz.newInstance();
// Catch and log any exception thrown
} catch (Exception exceptThrown) {
exceptThrown.printStackTrace();
return null;
}
// Loop through all of the methods in the class
for (Method method : BankInstruction.class.getMethods()) {
// Check if we have a set method
if (method.getName().substring(0, 3).equalsIgnoreCase("set")) {
// Create a corresponding get method
String getMethodName = method.getName().replace("set", "get");
// Check if we have a get method for the set method variable
if (Arrays.toString(BankInstruction.class.getMethods()).contains(getMethodName)) {
// Get the method from the method name
Method getMethod = getMethodFromName(BankInstruction.class, getMethodName);
try {
// If we have a method proceed
if (getMethod != null) {
// Attempt to invoke the method and get the response
Object getReturn = getMethod.invoke(incoming);
// If we have a response proceed
if (getReturn != null) {
// Attempt to invoke the set method passing it the object we just got from the get
method.invoke(outgoing, getReturn);
}
}
} catch (Exception except) {
except.printStackTrace();
}
}
}
}
// Return the found object
return outgoing;
}
可能不是最好的解決方案,但它是爲我工作。
這是沒有意義與鑄造做到這一點,所以,不,你不能。您需要編寫一些轉換代碼,從代碼的類型創建您感興趣的類型的新對象。這些問題暗示是其最好由你,告訴你正在試圖解決,而不是如何你試圖解決它的整體問題就解決了一個可能的[XY問題(http://xyproblem.info/)類型的問題,因爲你可能會吠叫錯誤的樹。 –
如果'ClassC'需要初始化'ClassB'沒有的屬性呢? – tadman
在我們的例子中,我們有一個DTO對象被映射到一個數據庫對象中,然後用來插入到數據庫中。我只是希望不必創建對象的轉換/翻譯。 –