Yonatan
Yonatan

Reputation: 93

help with reflections and annotations in java

I'm having trouble with doubling up on my code for no reason other than my own lack of ability to do it more efficiently...

for (Method curr: all){
        if (curr.isAnnotationPresent(anno)){
            if (anno == Pre.class){
                for (String str : curr.getAnnotation(Pre.class).value()){
                    if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){
                        toRun.add(curr);
                    }
                }
            } if (anno == Post.class) {
                for (String str : curr.getAnnotation(Post.class).value()){
                    if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){
                        toRun.add(curr);
                    }
                }
            }
        }
    }

anno is a parameter - Class<? extends Annotation>, and Pre and Post are my annotations, both have a value() which is an array of strings.

Of course, this is all due to the fact that i let Eclipse auto fill code that i don't understand yet.

Upvotes: 0

Views: 312

Answers (1)

Chris
Chris

Reputation: 10445

If by 'more efficiently' you mean 'in fewer lines of code', then why not merge the two if statements? The only difference I can see between them is one has Pre.class where the other has Post.class, and you already have that class reference conveniently in the anno var:

for (Method curr : all) {
    if (curr.isAnnotationPresent(anno)) {
        if (anno == Pre.class || anno == Post.class){
            for (String str : curr.getAnnotation(anno).value()){
                if (str.equals(method.getName()) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0){
                    toRun.add(curr);
                }
            }
        }
    }
}

Further to that, there's no point in doing the outer for loop if anno is neither Pre.class nor Post.class, so you should do that check outside (this saves iterating over the methods if it's called with an annotation you don't want). You can also move the checks for the returnType and parameter length outside the inner for loop (this saves repeating them for each of the values, and saves iterating at all if they're not true).

 if (anno == Pre.class || anno == Post.class){
    for (Method curr : all) {
        if (curr.isAnnotationPresent(anno) && curr.getReturnType() == boolean.class && curr.getParameterTypes().length == 0) {
            for (String str : curr.getAnnotation(anno).value()){
                if (str.equals(method.getName())) {
                    toRun.add(curr);
                }
            }
        }
    }
}

Upvotes: 2

Related Questions