Java反射不同意方法声明

时间:2010-12-20 23:23:57

标签: java reflection struts

抱歉这个问题的长度。我是Java的新手,我遇到了一些让我很难过的东西。我是Java的新手,我甚至不知道所有的术语,所以请耐心等待我;我有大约3年的PHP经验(主要是程序性的,不是OO),但是Java很少。我也知道使用System.out.println进行调试是错误的方法,但它可以工作,这就是我习惯的(如果你必须在这里插入关于PHP程序员的笑话)。我还在试图弄清楚如何使用NetBeans调试器。

我正在为使用Struts(1.x)的Web应用程序添加一项功能。我遇到的问题似乎是声明一个方法需要传递给它的String,但对该方法执行Reflection表示它需要String [](一个字符串数组)。我受到限制,因为我无法对应用程序进行重大的结构更改,当然我必须确保我不会破坏当前正在运行的应用程序中的任何内容,所以我正在努力使我的在那里已经存在的变化。那么,对于这个问题......

这是声明方法的地方(从这些方法中删除了很多行,只显示我希望的相关位):

AEReportBean.java:

public class AEReportBean {
    private String selectedDownloadFields = null;

    public String getSelectedDownloadFields() {
        return selectedDownloadFields;
    }

    // Note that there is no overloading of this function anywhere, this is the only declaration.
    public void setSelectedDownloadFields(String selectedDownloadFields) {
        this.selectedDownloadFields = selectedDownloadFields;
    }
}

当用户在表单上单击“提交”时,它将由AEReportSubmitAction.java处理:

public class AEReportSubmitAction extends BaseAction {
    public ActionForward doExecute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response
        ) throws Exception {
        // This works fine, the paramater is getting passed in the request:
        System.out.println("URL parameter: " + request.getParameter("selectedDownloadFields");

        AEReportBean bean = new AEReportBean(request.getLocale(), 0);

        PropertyUtil.setAllFromRequest(request, bean);
        // This prints "Null", meaning the setAllFromRequest line above is failing to set this property.
        System.out.println("AEReportSubmitAction.java - bean.getSelectedDownloadFields() after setAllFromRequest: " + bean.getSelectedDownloadFields());
    }
}

PropertyUtil.setAllFromRequest()是魔术和真正问题发生的地方:

public class PropertyUtil {
    /**
     * Takes all the parameters from the request object and if there's a matching
     * mutator method in the bean, sets it
     */
    static public void setAllFromRequest(ServletRequest request, Object out) {
        // Iterate through all the request parameter names and try to set each one.
        for (Enumeration parameterNames = request.getParameterNames(); parameterNames.hasMoreElements();) {
            String name = (String) parameterNames.nextElement();
            try {
                PropertyUtil.setSimpleProperty(out, name, request.getParameter(name));
            }
            catch (Exception e) {
                log.info("Exception while setting properties from the Request. parameterName=" + name, e);
            }
        }
    }

    /**
     * Sets the property from an object using the object's mutator method.
     * Assumes naming conventions for accessor methods
     * @param bean the object to get the property from
     * @param property the name of the property to obtain
     * @param newProperty the object to set
     */
    // NOTE: This just seems to be a wrapper for the method below it...
    static public void setSimpleProperty(Object bean, String property, Object newProperty) throws Exception {
        PropertyUtil.setSimpleProperty(bean, property, newProperty, null);
    }

    /**
     * Sets the property from an object using the object's mutator method.
     * Assumes naming conventions for accessor methods
     * @param bean the object to get the property from
     * @param property the name of the property to obtain
     * @param newProperty the object to set
     */
    static public void setSimpleProperty(Object bean, String property, Object newProperty, Class type) throws Exception {
        // Capitalize the first letter in the property and append "set" to the front
        String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
        Method method;

        Class[] parameters;

        // If the Type was passed in when this method was called, simply add it to the Class array.
        if (type != null) {
            parameters = new Class[]{type};
        }
        // If the Type was not specified, determine the Type's class by calling getClass() on it; that class will be used below to call the appropriate setter method.
        else {
            parameters = new Class[]{newProperty.getClass()};
        }

        // Here's the reflection problem...
        // Iterate through all the methods in the bean.  If the method is named "setSelectedDownloadFields", print out some info about it.
        for (Method m : bean.getClass().getMethods()) {
            if (m.getName().equals("setSelectedDownloadFields")) {
                // newProperty is the incoming data that ultimately comes from the HTML form field.
                System.out.println("newProperty.getClass(): " + newProperty.getClass()); // Prints "class java.lang.String"

                    // Added for Cameron Skinner in comments.
                    System.out.println("m.toGenericString: " + m.toGenericString()); // Prints "public void com.[company deleted].bean.AEReportBean.setSelectedDownloadFields(java.lang.String[])"

                System.out.println("m.getName(): " + m.getName()); // Prints "setSelectedDownloadFields"
                System.out.println("parameters:");
                for (Class c : m.getParameterTypes()) {
                    System.out.println("--c.getCanonicalName(): " + c.getCanonicalName()); // Prints "java.lang.String[]"
                    System.out.println("--c.getName(): " + c.getName()); // Prints "[Ljava.lang.String;"
                }
            }
        }


        // And here's where it fails...
        try {
            System.out.println("bean.getClass(): " + bean.getClass());  // Prints "class com.[company deleted].bean.AEReportBean"
            System.out.println("methodName: " + methodName); // Prints "setSelectedDownloadFields"
            System.out.println("for (Class p : parameters):");
            for (Class p : parameters) {
                System.out.println("--p.getCanonicalName(): " + p.getCanonicalName()); // Prints "java.lang.String"
            }

            // Here it looks for a method called, effectively, AEReportBean.setSelectedDownloadFields(String s), but above we see that reflection is showing it as AEReportBean.setSelectedDownloadFields(String[] s), so the try block fails.
            method = bean.getClass().getMethod(methodName, parameters);
        }
        catch (NoSuchMethodException e) {
            // All lines below here also fail until it bombs out with the exception at the bottom...

            // If no method can be found, then see if it's a primitive type that
            // has been wrapped
            Class valueClass = newProperty.getClass();
            //System.out.println("valueClass.toString() = " + valueClass.toString());
            try {
                if (valueClass.equals(Integer.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{int.class});
                }
                else if (valueClass.equals(Double.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{double.class});
                }
                else if (valueClass.equals(Long.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{long.class});
                }
                else if (valueClass.equals(Float.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{float.class});
                }
                else {
                    throw new Exception(e.getMessage());
                }
            }
            catch (NoSuchMethodException ex) {
                throw new Exception(ex.getMessage());
            }
        }

        // If it had gotten to this point, it would call the method with the appropriate parameters, and the property would be set.
        try {
            // Now execute the method
            method.invoke(bean, new Object[]{newProperty});
        }
        catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }
}

我真的不知道我在这里缺少什么,但必须有一些东西。同一页面上的其他HTML表单元素完美运行。如果需要更多信息,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:4)

代码结果不是谎言。它基本上告诉我们这个课程不是你所期望的。您在项目的类路径中有多个AEReportBean个不同版本的类,可能在不同的包中,并且在类加载中导入了错误的类或优先级。在Netbeans中进行类型/类搜索,以在类路径中按给定名称查找所有类(我不做Netbeans,但在Eclispe中它是Ctrl + Shift + T,Netbeans等效可能是Alt + Shift + O )

更新:另一个可能的原因是Netbeans在保存源文件时没有自动构建项目(IDE应该在构建期间创建/刷新.class文件)。看看设置中的某个地方。