2013-04-26 59 views
1

当我检查使用java反射的类中的方法的参数java.math.BigDecimaljava.lang.StringisPrimitive()返回false。是的,他们不是原始的,但i want to differnciate between user defined class and these java classJava - BigDecimal和Reflection

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); 
          } 

基于上面的代码我设置的假methodParams.setPrimitive(true);真的,我已经这样做了,因为只有少数情况下,我得到的用户定义的对象,在我的情况com.hexgen.ro.request.CreateOrderRO

所以如何设置?

也使用反射我得到的类的名字,它声明的方法和参数的键入方法。

,但我没能获得参数名称一样,如果我已经宣布类似下面的方法:

class test{ 
    public String testMethod(int a, String b){ 
    return "test"; 
    } 

} 
在上面的代码中,我能够得到folloing

Class name : test 
Method name : testMethod 
Arguments Type : int and String 

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

如何做到这一点。

请帮我完成这件事。

问候

+0

我不相信Java字节码保留方法参数的**名称**。 – 2013-04-26 05:26:59

+0

不错,比它的意思是说这是不可能的吧? – 2013-04-26 05:28:52

+1

请参阅http://stackoverflow.com/questions/2237803/can-i-obtain-method-parameter-name-using-java-reflection – 2013-04-26 05:31:04

回答

2

没有特殊标志由用户定义的类象CreateOrderRO区分像BigDecimal一个Java API类。你将需要检查他们的软件包名称或跟踪一组你想与别人区别对待的类。

要回答你的第二个问题,方法参数的名称不保持在运行。这反映在一个事实上,即一个Method只能报告其参数的形式类型,而不是它们所称的参数。

编辑:它看起来像在运行时发现方法的参数名称为可能的,但前提是与调试信息编译和使用类似Spring的ParameterNameDiscoverer。看到这个职位的更多细节:Getting the name of a method parameter(信贷到PM 77-1's comment)。恕我直言,任何需要编译调试信息的严肃解决方案都是严重的设计缺陷。

1

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

否则参数名称不会保留。

为了区分用户定义的类,您可以检查包名。您可以维护一个列表包,您希望按照用户定义的方式定义列表包,或者维护您没有定义为用户定义的包列表。

原因是,如果你使用任何第三方库,然后这些库的类用户为您或不定义?

1

你可以有一个方法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; 
}