3

i have a method in a class like this:

public static void postEvents(List<RuleEvent> eventList) {
    for(RuleEvent event:eventList)
        if(canProcess(event))
            findListenerAndPost(event);
    }

and i want to access it using reflection like this:

Class partypes[] = new Class[1];
partypes[0] = List.class;    //does not find the method as it is of List<RuleEvent>
postMethod = cls.getMethod("postEvents", partypes);

so, how do I get the class object of List<RuleEvent>????

I already know the way of ((List<RuleEvent>) new ArrayList<RuleEvent>()).getClass() but there should be a more direct way...

10
  • 3
    Works fine for me. Do you get an error? Due to type erasure there isn't a List<RuleEvent> at runtime. Commented Jan 2, 2012 at 14:09
  • i just dont find the method. it comes as null Commented Jan 2, 2012 at 14:10
  • 1
    Is cls the right class? Null?! You should get a NoSuchMethodException if the method doesn't exist. Commented Jan 2, 2012 at 14:11
  • 2
    I don't think using a new ArrayList<RuleEvent>().getClass() works either - first of all, since it returns an ArrayList.class rather than List.class, and second, because of type erasure, it still returns a raw ArrayList.class object. Commented Jan 2, 2012 at 14:19
  • 1
    No, because at runtime, all the generic type information is erased. So the method signature in the JVM is actually postEvents(List). Commented Jan 2, 2012 at 14:29

1 Answer 1

9

All you need is the following

cls.getMethod("postEvents", List.class).invoke(null, eventList);

The generic type is not required at runtime.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.