3

Given a class Something with a constructor public Something(List<String> l), I would like to use klass.getConstructor(parameterTypes) where parameterTypes[0] is the class java.util.ArrayList (because I need to "match" a given specific instance) and not the interface java.util.List.

This doesn't work (NoSuchMethodException), because Java Reflection appears to need an EXACT type class match. What is the best way around this?

2 Answers 2

7

Might be overkill, and admittedly could pick up too many constructors:

Constructor[] constructors = klass.getConstructors();
for(Constructor constructor:constructors) {
      Class<?>[] params = constructor.getParameterTypes();
      if(params.length == 1 && params[0].isAssignableFrom(ArrayList.class) {
          //Yep could be the one you want.
      }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes of course indeed; thank you very much. Done in github.com/vorburger/vorburgers-blueprints/blob/master/… FTR java.beans.ReflectionUtils has stuff like that as well, but is not public; code.google.com/p/reflectutils/source/browse/trunk/src/main/… of code.google.com/p/reflectutils has an even better version.
0

Reflection only will find methods that are actually declared. If the constructor is declared to take List, that's the only constructor there is. There's no such concept as 'matching a specific instance' when using reflection. If you had two constructors, one taking List and one taking ArrayList, then you could grab either one via getConstructor.

I don't see why you think you need this. If you call newInstance, and then you use getConstructor on the declared List type, then you can pass it an instance of ArrayList.

2 Comments

uhm, well I do need it ;) The answer above was helpful.
Class.getMethod(Class...) will find "matching methods" much like the compiler. So reflection is not completely impotent. I'm still confused why Sun decided to make getMethod(..) use parameter matching, but getConstructor(..) won't.

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.