Java通过反射获取参数值



我有一组非常相似的类。目前,我正在使用反射来访问和调用下面的select方法。我需要得到的是myList参数。我尝试过使用代理,但我是Java的初学者,不知道如何实现和使用它们。

public int choose(List<Object> myList, Object card, Object color, State state)
{
      int answer = -1;
      // sort through myList and set answer to index of desired object
      return answer;
} 

有没有更好的方法可以在不使用AspectJ的情况下在Java中获得这个参数?如果是的话,你能举个例子吗?

谢谢你的帮助。

class State
{
}
class MyClass
{
    public int choose(List<Object> myList, Object card, Object color, State state)
    {
        int answer = -1;
        System.out.println("myList has " + myList.size() + " elements");
        for (Object o : myList)
        {
            System.out.println("element -> " + o);
        }
        // sort through myList and set answer to index of desired object
        return answer;
    }
}
public static int InvokeChoose(Object obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException
{
    Method m = obj.getClass().getDeclaredMethod("choose", List.class, Object.class, Object.class, State.class);
    List<Object> someList = new ArrayList<>();
    someList.add(Integer.valueOf(0));
    someList.add(Integer.valueOf(1));
    someList.add(Integer.valueOf(2));
    Object result = m.invoke(obj, someList, new Object(), new Object(), new State());
    return ((Number)result).intValue();
}
public static void TryIt()
{
    MyClass c = new MyClass();
    try
    {
        int result = InvokeChoose(c);
        System.out.println("the result is: " + result);
    }
    catch (Throwable e)
    {
        e.printStackTrace();
    }
}

输出:

myList has 3 elements
element -> 0
element -> 1
element -> 2
the result is: -1

相关内容

  • 没有找到相关文章

最新更新