Java - BigDecimal and Reflection



当我检查方法的参数,这是在一个类使用java反射java.math.BigDecimaljava.lang.String isPrimitive()返回false。是的,它们不是原始的,但i want to differnciate between user defined class and these java class

Class[] parameterTypes = method2.getParameterTypes();
for (Class class1 : parameterTypes) { // check the parameter type and put them in to a ArrayList
                                    methodParams = new MethodParams();
                                    strClassNameToFix = class1.getName();
                                    strClassname =strClassNameToFix.replaceAll("\[L", "").replaceAll("\;","");
                                        methodParams.setDataType(strClassname);
                                        if(class1.isArray()){
                                            methodParams.setArray(true);
                                        }
                                        if(class1.isPrimitive()){
                                            methodParams.setPrimitive(true);
                                        }
                                        tempParamsList.add(methodParams);
                            }

基于上面的代码,我设置true或false methodParams.setPrimitive(true);,我这样做是因为很少有情况下,我得到用户定义的对象,在我的情况下,com.hexgen.ro.request.CreateOrderRO

怎么设置呢?

也使用反射,我得到类名,其中声明的方法和方法的参数类型。

但是我不能得到参数的名称,如果我已经声明了一个方法,像下面:

 class test{
    public String testMethod(int a, String b){
    return "test";
    }
}
在上面的代码中,我能够得到以下
Class name : test
Method name : testMethod
Arguments Type : int and String

但是i also want to get int a and String b类型的参数以及声明的变量名

如何做到这一点。

请帮我把这件事做完。

没有特殊的标志来区分像BigDecimal这样的Java API类和像CreateOrderRO这样的用户定义类。您需要检查它们的包名,或者跟踪一组您希望与其他类区别对待的类。

回答你的第二个问题,方法参数的名称在运行时不维护。这反映在以下事实中:Method只能报告其参数的形式类型,而不能报告它们的名称。

EDIT:看起来在运行时发现方法参数名是可能的,但只有在使用调试信息编译并使用Spring的ParameterNameDiscoverer之类的东西时才有可能。获取方法参数的名称(参考PM 77-1的评论)。在我看来,任何需要编译调试信息的解决方案都是一个严重的设计缺陷。

如果使用调试信息进行编译,则可以获得参数名称。可以使用-g参数

进行编译和调试。

否则不保留参数名。

为了区分用户定义的类,您可以检查包名。你可以维护一个你想要定义为用户定义的包列表,或者维护一个你不想定义为用户定义的包列表。

原因是如果你正在使用任何第三方库,那么这些库的类是为你定义的还是不是?

您可以有一个方法isPrimitive()(尽管我想要一个更好的名称,使用您使用的相同的名称),它将做这样的事情:

boolean isPrimitive(Class class1) throws ClassNotFoundException {
    String className = class1.getName();
    if (className.equals("java.math.BigDecimal")|| className.equals("java.lang.String")) {
        return true;
    }
    return false;
}

最新更新