Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out what a method's visibility is via reflection?

Context:

I'm trying to learn/practice TDD and decided I needed to create an immutable class.

To test the 'immutability invariant' (can you say that?) I thought I would just call all the public methods in the class via reflection and then check that the class had not changed afterwards. That way I would be unlikely to break the invariant carelessly later on. This may or may not be practical/valid in itself but I thought it would also be an exercise in reflection for me.

Strategies:

  • Use getMethods():

Using getMethods(), I get the public interface only, but of course this includes all the inherited methods as well. The problem then is that methods such as wait() and notify() cause InvocationTargetExceptions because I haven't synchronized etc...

  • Use getDeclaredMethods():

(Naively?) assuming that only the methods that I declare are able to break the class's immutability, I tried using getDeclaredMethods() instead. Unfortunately this calls all methods, private and public that are declared in the class, but not super classes. The private methods obviously are not relevant as they are allowed to break immutability.

Question:

So my question is, how can I find out whether a method obtained via getDeclaredMethods() is public or not so that I can invoke it via reflection? Nothing jumped out at me looking through the docs...

I can see other ways of solving this problem like specifically ignoring methods like wait() etc but that seems even hackier than I can handle.

like image 919
mallardz Avatar asked May 21 '14 15:05

mallardz


2 Answers

As mentioned in the comments, you can use Method.getModifiers() to determine the modifiers associated with the method.

E.g.

if (Modifier.isPublic(someMethod.getModifiers()) {
  // etc.
}
like image 89
2 revs Avatar answered Oct 23 '22 15:10

2 revs


There is another way to do this. If you do something like Modifier.toString(m.getModifiers()); it will return a string of the visibility. This is useful if you are just trying to figure out the visibility. If you are trying to test for a specific type (Like only doing something if the visibility is public), then the other answer provided here works just as well!

like image 21
Connor Avatar answered Oct 23 '22 13:10

Connor