2016-09-29 17 views
0

我有一個簡單的問題。我想要String.TYPE作爲parameterTypegetDeclaredMethod()但我找不到它。例如對於Long數據類型有Long.TYPE,但對於String類型沒有任何類似的東西。 有人可以幫助我嗎? 感謝Java getDeclaredMethod()parameterTypes字符串參數

Object newClass; 
newClass = Class.forName(cls.getName()).getConstructor().newInstance(); 
      for (Method m : cls.getClass().getMethods()) 
       if (m.getName().startsWith("get") && m.getParameterTypes().length == 0) { 
        try { 
         //final Object r = m.invoke(cls); 
         String MethodName=m.getName().replace("get",""); 

         if (m.getReturnType().equals(Long.TYPE)){ 
         // Class<?> c = Class.forName("class name"); 

         }else 
         { 
          String value =this.getString(j,MethodName); 
          Method method = cls.getDeclaredMethod (MethodName, String);//Here I need Parameter Type for string imput parameter 
          method.invoke (newClass, value); 
         } 


        } catch (IllegalAccessException e) { 
         e.printStackTrace(); 
        } catch (InvocationTargetException e) { 
         e.printStackTrace(); 
        } 
        // do your thing with r 
       } 
+0

我會建議使用.class,將工作。您不必進入.TYPE。 – cody123

回答

1

選中此項。它工作正常。

Test obj = new Test(); 
     for (Method m : obj.getClass().getDeclaredMethods()){ 
      if (m.getName().startsWith("get") && m.getParameterTypes().length == 1) { 
       System.out.println("==="+m.getName()); 
       if (m.getReturnType().equals(String.class)) { 
        String value = "ABCD"; 
        Method method = Test.class.getDeclaredMethod (m.getName(), String.class); 
        method.invoke (obj, value); 
       } 
      } 
     } 
1

Long.TYPE是原始類型long

對於像String這樣的引用類型沒有這種東西。

您想要String.class。 (Long.class將用於盒裝類型Long)。