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.