8

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.

4
  • 1
  • 2
    @JBNizet Why not just make this the answer?
    – Mark W
    May 21, 2014 at 15:15
  • @MarkW 1. laziness. 2. to make the OP realize that simply reading the javadoc allows answering such a question.
    – JB Nizet
    May 21, 2014 at 15:17
  • 1
    @JBNizet What Mark said. I guess I need to look a little more deeply at the docs. I did look at them and as I said, nothing 'jumped out at me'! If you don't want to add an answer I'm happy to do it myself.
    – mallardz
    May 21, 2014 at 15:18

2 Answers 2

22

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

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.