java – Reflections: parsing method modifiers

Question:

I need to extract protected methods from the class. I get the array Method[] from the Class.getDeclaredMethods() method, then parse the array objects. There is a Method.getModifiers() method that returns, as I understand it, one of the static constants of the Modifier class. The trick is that a method can have several modifiers (of the public static type), but I have only one at my disposal. How is that?

Answer:

The getModifiers() method returns a bit mask – the simplest way to represent a set of values ​​(a kind of EnumSet for the poor). Each individual modifier in this bit mask is a separate bit. For example, public is the least significant (zero) bit, private is the next (first) bit, and so on. To check if the i-th bit in the bit mask is set, it is necessary to check for zero the result of the operation (modifiers & (1 << n)) , where n is the bit number. To simplify, usually for possible values (1 << n) suitable constants are set, which are just in the Modifier class:

  • Modifier.PUBLIC = 1 << 0 = 1
  • Modifier.PRIVATE = 1 << 1 = 2
  • Modifier.PROTECTED = 1 << 2 = 4

Etc. Accordingly, to find out, for example, whether a method is declared protected , you need to check the condition method.getModifiers() & Modifier.PROTECTED != 0 . This is exactly what the auxiliary static methods in the Modifier class do, so you can write it even easier: Modifier.isProtected(method.getModifiers()) .

Scroll to Top