meow
meow

Reputation: 28174

Java Reflection - Passing in a ArrayList as argument for the method to be invoked

would like to pass an argument of arraylist type to a method i am going to invoke.

I am hitting some syntax errors, so I was wondering what was wrong with what this.

Scenario 1:

// i have a class called AW
class AW{}

// i would like to pass it an ArrayList of AW to a method I am invoking
// But i can AW is not a variable
Method onLoaded = SomeClass.class.getMethod("someMethod",  ArrayList<AW>.class );
Method onLoaded = SomeClass.class.getMethod("someMethod",  new Class[]{ArrayList<AnswerWrapper>.class}  );

Scenario 2 (not the same, but similar):

// I am passing it as a variable to GSON, same syntax error
ArrayList<AW> answers = gson.fromJson(json.toString(), ArrayList<AW>.class);

Upvotes: 4

Views: 12671

Answers (2)

gk5885
gk5885

Reputation: 3762

Class literals aren't parameterized in that way, but luckily you don't need it at all. Due to erasure, there will only be one method that has an ArrayList as a parameter (you can't overload on the generics) so you can just use ArrayList.class and get the right method.

For GSON, they introduce a TypeToken class to deal with the fact that class literals don't express generics.

Upvotes: 2

Yohanes Gultom
Yohanes Gultom

Reputation: 3842

Your (main) mistake is passing unnecessary generic type AW in your getMethod() arguments. I tried to write a simple code that similar to yours but working. Hopefully it may answers (some) of your question somehow :

import java.util.ArrayList;
import java.lang.reflect.Method;

public class ReflectionTest {

  public static void main(String[] args) {
    try {
      Method onLoaded = SomeClass.class.getMethod("someMethod",  ArrayList.class );
      Method onLoaded2 = SomeClass.class.getMethod("someMethod",  new Class[]{ArrayList.class}  );    

      SomeClass someClass = new SomeClass();
      ArrayList<AW> list = new ArrayList<AW>();
      list.add(new AW());
      list.add(new AW());
      onLoaded.invoke(someClass, list); // List size : 2

      list.add(new AW());
      onLoaded2.invoke(someClass, list); // List size : 3

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

}

class AW{}

class SomeClass{

  public void someMethod(ArrayList<AW> list) {
    int size = (list != null) ? list.size() : 0;  
    System.out.println("List size : " + size);
  }

}

Upvotes: 5

Related Questions