How can I find out what a method's visibility

2019-06-26 02:54发布

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.

2条回答
走好不送
2楼-- · 2019-06-26 03:10

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.
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-26 03:10

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!

查看更多
登录 后发表回答