Java反射 - 传入ArrayList作为要调用的方法的参数 [英] Java Reflection - Passing in a ArrayList as argument for the method to be invoked

查看:199
本文介绍了Java反射 - 传入ArrayList作为要调用的方法的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想将arraylist类型的参数传递给我要调用的方法。

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.

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

情景2(不一样,但相似):

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


推荐答案

你的(主要)错误是传递不必要的泛型类型<您的 getMethod()参数中的code> AW 。我试着写一个类似于你的简单代码但是工作。希望它可能以某种方式回答(某些)你的问题:

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

}

这篇关于Java反射 - 传入ArrayList作为要调用的方法的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆