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

走远了吗. 提交于 2019-12-10 16:55:05

问题


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.


回答1:


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.
}



回答2:


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!



来源:https://stackoverflow.com/questions/23787260/how-can-i-find-out-what-a-methods-visibility-is-via-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!