Java通过反射获取参数值

时间:2014-04-23 22:41:47

标签: java reflection parameters

我有一组非常相似的类。目前我正在使用反射访问并调用下面的选择方法。我需要的是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中获取此参数?如果是这样,你能提供一个例子吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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