cnsd007 2010-08-18 16:03
浏览 236
已采纳

关于java 反射问题

[code="java"]public static Customer setCustomerObject(String[] str)
throws IllegalArgumentException, SecurityException,
InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {

    Class<?> classType = new Customer().getClass();
    Field fields[] = classType.getDeclaredFields();
    Object objectCopy = classType.getConstructor(new Class[] {})
            .newInstance(new Object[] {});
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];

        String fieldName = field.getName();
        String firstLetter = fieldName.substring(0, 1).toUpperCase();

        // 获得和属性对应的setXXX()方法的名字
        String setMethodName = "set" + firstLetter + fieldName.substring(1);

        // 获得和属性对应的getXXX()方法

        // 获得和属性对应的setXXX()方法
        Method setMethod = classType.getMethod(setMethodName,
                new Class[] { field.getType() });
        // 获得 set方法参数的类型
        Class pvec = setMethod.getParameterTypes()[0];//

color=red]这里得到了 类型,是否可以根据这个类型 将 str[i] 转换为 该类型? 将一个泛类型向下转化为具体的类型,然后调用 这个类型的方法
将str[i] 转化 比如 Long.ValueOf(str[i])[/color]

System.out.println(pvec);
setMethod.invoke(objectCopy, str[i]);
}
return (Customer) objectCopy;
}[/code]

  • 写回答

4条回答 默认 最新

  • 「已注销」 2010-08-18 16:34
    关注

    不用转换,我使用Method.invoke(obj,new Object[]{arg1,args2})都是这么直接用。反射机制帮你搞定,咱们不容那么麻烦!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?