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

11,413

Solution 1

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);
  }

}

Solution 2

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.

Share:
11,413

Related videos on Youtube

meow
Author by

meow

Updated on October 10, 2022

Comments

  • meow
    meow over 1 year

    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);
    
    • JB Nizet
      JB Nizet over 11 years
      And the error message is? Have you read it?
    • barfuin
      barfuin over 11 years
      Have you tried doing it without the generic type arguments?
  • meow
    meow over 11 years
    it does! thanks. quick qn: what does this particular line mean? -> Class[]{ArrayList.class}
  • Yohanes Gultom
    Yohanes Gultom about 11 years
    it defines an array of Class with an ArrayList class as one of its member. Btw sorry for the (extremely) late reply..