-1
だから、子供に子供をキャストするためのJavaでの方法がありますそれを直接行うのではなく、c.setField1(b.getField1)のようなすべてのフィールドを持つトランスレータを記述する必要がない方法があります。私は以下の持っていた場合
だから、子供に子供をキャストするためのJavaでの方法がありますそれを直接行うのではなく、c.setField1(b.getField1)のようなすべてのフィールドを持つトランスレータを記述する必要がない方法があります。私は以下の持っていた場合
子供を子供にキャストすることや、子供を親にキャストしてから親に戻すことはできません。そこで、BankInstructionの1つの子クラスから別の子クラスにすべてのデータをコピーする汎用トランスレータを作成しました。
/**
* 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オブジェクトをデータベースオブジェクトにマップしてからデータベースに挿入する方法を示します。私は、オブジェクトの変換/変換を作成する必要がないことを望んでいました。 –