2016-12-13 26 views
0

如何使用文字为java.lang.Class.getMethod定义参数类型?如何为任意类的数组的类编写文字

public class NewTester 
    { 
     public static void main(String[] args) 
     { 
      System.out.println("START"); 
      Worker myWorker = new Worker(); 
      Thing[] argument = new Thing[] { new Thing("book"), 
              new Thing("pencil") }; 
      Object[] arguments = new Object[] { argument }; 

          // HOW ABOUT LITERALS HERE INSTEAD OF getClass 
      Class<?>[] parameterTypes = new Class<?>[] { argument.getClass() }; 

      Method myMethod; 
      try 
      { 
       myMethod = myWorker.getClass().getMethod("work", parameterTypes); 
      } 
      catch (NoSuchMethodException | SecurityException e) 
      { 
       throw new RuntimeException(e); 
      } 
      try 
      { 
       myMethod.invoke(myWorker, arguments); 
      } 
      catch (IllegalAccessException | 
        IllegalArgumentException | 
        InvocationTargetException e) 
      { 
       throw new RuntimeException(e); 
      } 
      System.out.println("END"); 
     } 

     private static class Worker 
     { 
      @SuppressWarnings("unused") 
      public void work(Thing[] argument) 
      { 
       assert argument.length == 2; 
       assert argument[0].value.equals("book"); 
       assert argument[1].value.equals("pencil"); 
      } 
     } 

     private static class Thing 
     { 
      String value; 
      Thing(String value) 
      { 
       this.value = value; 
      } 
     } 
    } 

我尝试了以下方法,但是在使用NoSuchMethodException的getMethod调用中失败。

Class<?>[] parameterTypes = new Class<?>[] { java.lang.reflect.Array.class }; 
+0

我不知道我是否理解你的问题,但看起来你可能正在寻找'Thing [] .class'。 – Pshemo

+0

是的。谢谢。我不认为这是可行的,因为我强制使用括号。 '(Thing []).class'没有编译。你的确如此。 – H2ONaCl

回答

1

要获得Class字面代表一些Type你可以写Type.class。对于数组,使用Type[].class

相关问题