jeudi 5 mai 2016

How can I copy a java.lang.reflect.Method?

I have an API that takes in a Method and stores it to call later. In order to invoke it I have to do setAccessible(true). Before I do that, I'd like to make a defensive copy. But how?

I thought of

method.getDeclaringClass()
      .getDeclaredMethod(method.getName(), method.getParameterTypes());

but that won't necessarily give me the same method back in the presence of bridge methods (or other cases where two methods have the same name/parameter types but different return types).

I could loop over method.getDeclaringClass().getDeclaredMethod() and look for an exact match, but that seems inefficient.





Aucun commentaire:

Enregistrer un commentaire