1

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
  • 3
    Show us the actual reflection code. It should work. Commented Nov 18, 2009 at 1:59
  • On the other hand, if you had a T foo(R input) then the signature after erasure would be foo(Object) for reflection; note the return type is not part of the signature. Commented Feb 24, 2012 at 6:56

2 Answers 2

6
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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.