2011-09-19 56 views
0

我只是使用方法反射API创建一个通用方法。在这种方法中,我试图得到一个微粒方法(getter方法/ setter方法)的值,但我卡住,我不知道如何做到这一点。我是阿贝尔获得所有的方法名称使用方法反射API但不是亚伯得到该方法的价值。所以请帮助我。如何使用反射从POJO中获得价值?

这里是我的代码......

/*
propertyNames列表是包含两个记录。

and that records are two different EntityName(Variable Name) 

    ex. in my class i have declared two Entity(Variable) 
    private Integer productId; 
    private Integer bomBucket; 

    so propertyNames List is contain [productId , bomBucket] this two records. 

*/

public <T>void fillList(List<String> propertyNames , T clas){ 

    try{ 
     for(Object entity : entities.keySet()){ 
      if(propertyNames != null && propertyNames.size() > 0){ 
       Method[] methodList = clas.getClass().getMethods(); 
       Method methodName; 
       for (String propertyName : propertyNames) { 
        for(Method method : methodList){ 
         if(method.getName().trim().startsWith("set")){ 
          if(propertyName.trim().equalsIgnoreCase(method.getName().substring(3, method.getName().trim().length()))){ 

           methodName = clas.getClass().getMethod(method.getName().trim(),new Class[]{Integer.class}); 

           System.out.println("HERE I GET METHOD NAME ::: " + methodName.getName()); 

           /* 
           * here one by one i am getting all the Setter methods name from the class . 
           * but i want a that Setter methods values. Not return type. 
           */ 
          } 
         } 
        } 
       } 
      } 
     } 

    }catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

你可以发布代码吗?你的问题几乎没有意义。 –

+0

我添加了我的代码,请检查它。 –

回答

0

你是什么“时,方法的价值”的意思是你的意思是方法的返回类型,或者你想调用该方法,在某些情况下的它的父类,也许有一些argumetns,然后得到它返回的值?在这种情况下,如果你的方法是不公开的,你必须先调用setAccessible(真)的方法对象调用之前:

//get instance of the class that has your method 
    DsrProcessor dsrProcessor = DsrProcessor.class.newInstance(); 
    //get method object (by passing in it's name and the list of argument types he's accepting - echo(String): 
    Method m = DsrProcessor.class.getMethod("echo", String.class); 
    //use reflection to invoke the method passing the instance of it's class and a list of arguments : 
    String methodReturnValue = (String) m.invoke(dsrProcessor, "Hello"); 
    //do something with what the method returned 
    System.out.println(methodReturnValue);//prints: "echo:hello" 
0

您还可以使用java.beans.Introspector中类和一个它的getBeanInfo方法。 它返回引用所有属性描述符java.beans.PropertyDescriptor的BeanInfo实例。

+0

比你的答案,但我也使用PropertyDescriptor,但我仍然没有得到任何解决方案。 –