views:

54

answers:

2

Given this method:

public final void foo (List<MyClass> bar){ .. }

I want to be able to call this method reflectively. In order for getMethod to work, I have to change it to:

public final void foo (List bar){ .. }

This does not seem right for obvious reasons, but no combination of inputs to getMethod seem to work otherwise. I have searched high and low on Google to no avail. Any advice?

Cheers and Thanks!

+2  A: 

Works for me.

import java.util.ArrayList;
import java.util.List;

public class Argh
{
    public void foo(final List<Argh> arghs)
    {
     System.out.println("Received " + arghs);
    }

    public static void main(final String[] args) throws Exception
    {
     Argh.class.getMethod("foo", List.class).invoke(new Argh(), new ArrayList<Argh>());
    }
}
Jonathan Feinberg
+5  A: 
import java.util.*;
import java.lang.reflect.*;
public class Test {
    public final void foo (List<String> bar){
        for(String x : bar)
            System.out.println(x);
    }
    public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Test x = new Test();
        List<String> y = new ArrayList<String>(); y.add("asd"); y.add("bsd");
        x.getClass().getMethod("foo",List.class).invoke(x,y);
    }
}

You can just use getMethod("foo",List.class) and use List.class as the generic information List<String> is only used at compile time. At runtime the method signature will look like

public final void foo (List bar)

as on compile-time type erasure gets rid of the generic info.

jitter