jeudi 26 février 2015

Invokable.getReturnType(): cannot reproduce Guava's example from the official wiki

In the official Guava's TypeToken wiki, there is the following example:



Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
invokable.getReturnType(); // String.class


How getMethod is set?


I tried the following examples:




  1. First try:



    List<String> list = new ArrayList<String>();
    Class[] arg = { int.class };
    Method getMethod = list.getClass().getMethod("get", arg);
    Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
    System.out.println(invokable.getReturnType());


    It crashed with the following message:



    Exception in thread "main" java.lang.IllegalArgumentException: public java.lang.Object java.util.ArrayList.get(int) not declared by java.util.List<java.lang.String>
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:145)
    at com.google.common.reflect.TypeToken.method(TypeToken.java:495)
    at tmp.LaunchClass.main(LaunchClass.java:28)



  2. Second try (a little bit different though):



    List<String> list = new ArrayList<String>();
    Class[] arg = { int.class };
    Method getMethod = list.getClass().getMethod("get", arg);
    // changed here
    Invokable invokable = TypeToken.of(list.getClass()).method(getMethod);
    System.out.println(invokable.getReturnType());


    Doesn't crash, but doesn't return the expected result. Returned E. Expected result: String.class (as in the official wiki).








Aucun commentaire:

Enregistrer un commentaire