I have a class, which has a method calls all of the rest methods within the same class.
One way to do it is by using reflection framework, are there other ways?
[edit] Example code added:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AClass {
private void aMethod(){
}
private void bMethod(){
}
private void cMethod(){
}
private void dMethod(){
}
//50 more methods.
//method call the rest
public void callAll() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Method[] methods = this.getClass().getMethods();
for (Method m : methods) {
if (m.getName().endsWith("Method")) {
//do stuff..
}
}
}
}
I actually don't have a problem with calling all 4 methods from callAll(), i.e. avoid using reflection. But one of my colleagues pointed out that what if there are 50 methods, are you going to call them one by one? I don't have an answer for that, that's why I am asking the question here.
Thanks, Sarah
Actually, you'd probably want to use Class.getDeclaredMethods(). Class.getMethods() only returns public methods and none of the methods you show are public (and it also returns the public methods inherited from super classes).
That said: In the scenario you mention, reflection is a valid approach. All other (manual) approaches would be error-prone.
However, using a naming convention seems to weak to me as a guard. I'd write a custom annotation, and if that is present, I'd execute the method. Example:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RunMe {}
And here's your modified code:
public void callAll() throws
IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Method[] methods = this.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getAnnotation(RunMe.class)!=null) {
//do stuff..
}
}
}
I'm pretty sure that anything you end up doing is going to ultimately boil down to reflection anyways; eg: aspects, DI, etc. So I don't know what the gain would be - convenience maybe?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With