Java中是否存在将孩子投射到孩子身上的方法

时间:2017-09-25 20:57:17

标签: java casting

所以,如果我有以下内容:

public abstract ClassA {}

public class ClassB extends ClassA {}

public class ClassC extends ClassA {}

有没有办法执行以下操作:

ClassB b = new ClassB();
ClassC c = (ClassC)b;

我知道你不能直接这样做但是有一种方法可以避免编写一个包含c.setField1(b.getField1)等字段的翻译器。

1 个答案:

答案 0 :(得分:0)

不可能将孩子投射到孩子身上,也不可能将孩子投射到父母身上然后再回到父母身上。所以我编写了一个通用翻译器,将所有数据从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;

}

可能不是最好的解决方案,但它对我有用。