有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用反射时,如何在Java中映射和强制转换未知类型?

我使用反射将getter从一个类映射到另一个类中的setter,也就是说,stuts1使用表单类来显示大部分文本(字符串),后端使用纯Java对象来保存特定类型的值。我目前已经在getter和setter之间建立了映射,这很容易,但是我在混合类型方面遇到了问题。我使用setter中的参数类型来查看预期的类型,因此我需要从getter中确定对象的类型,并将其强制转换为预期的类型

例如

HomePageForm  ->   HomePageData 
Name="Alexei" ->   String name; (Maps correctly) 
Age="22"      ->   int age;     (Needs casting from string to int and visa-vera in reverse)

以下是我目前的代码

/**
     * Map the two given objects by reflecting the methods from the mapTo object and finding its setter methods.  Then 
     * find the corresponding getter method in  the mapFrom class and invoke them to obtain each attribute value.  
     * Finally invoke the setter method for the mapTo class to set the attribute value.  
     * 
     * @param mapFrom The object to map attribute values from
     * @param mapTo   The object to map attribute values to
     */
    private void map(Object mapFrom, Object mapTo) {
        Method [] methods = mapTo.getClass().getMethods();
        for (Method methodTo : methods) {
            if (isSetter(methodTo)) {
                try {
                    //The attribute to map to setter from getter
                    String attName = methodTo.getName().substring(3);

                    //Find the corresponding getter method to retrieve the attribute value from
                    Method methodFrom = mapFrom.getClass().getMethod("get" + attName, new Class<?>[0]);

                    //If the methodFrom is a valid getter, set the attValue
                    if (isGetter(methodFrom)) {
                        //Invoke the getter to get the attribute to set
                        Object attValue = methodFrom.invoke(mapFrom, new Object[0]);

                        Class<?> fromType = attValue.getClass();

                        //Need to cast/parse type here
                        if (fromType != methodTo.getParameterTypes()[0]){
                            //!!Do something to case/parse type!!
                        } //if

                        //Invoke the setter to set the attribute value
                        methodTo.invoke(mapTo, attValue);
                    } //if
                } catch (Exception e) {
                    Logger.getLogger(Constants.APP_LOGGER).fine("Exception in DataFormMappingService.map: "
                                                              + "IllegalArgumentException" + e.getMessage());
                    continue;
                }
            } //if
        } //for
    } //map

提前谢谢, 阿列克谢·布鲁


共 (1) 个答案

  1. # 1 楼答案

    我不是反射中的英雄,但我猜int是一种原始数据类型,而你的attValueObject类型

    你能试着把年龄的类型改成Integer,这样就可以把它转换成Object