2015-04-24 163 views
4

需要優化驗證碼:(Java)的if語句優化

import java.lang.annotation.Annotation; import java.lang.reflect.Method; import javax.ws.rs.CookieParam; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; ... private String valueParam(Annotation a) { String value = ""; if (a.annotationType() == QueryParam.class) { value = ((QueryParam) a).value(); } else if (a.annotationType() == PathParam.class) { value = ((PathParam) a).value(); } else if (a.annotationType() == CookieParam.class) { value = ((CookieParam) a).value(); } else if (a.annotationType() == HeaderParam.class) { value = ((HeaderParam) a).value(); } else if (a.annotationType() == MatrixParam.class) { value = ((MatrixParam) a).value(); } else if (a.annotationType() == FormParam.class) { value = ((FormParam) a).value(); } return value; }

SonarQube埋怨這種方法的複雜性。

改變並不那麼容易,因爲我們需要在獲取其值之前檢查註釋類型!

注意:陷阱位於沒有value()方法的Annotation接口上。

P.S. :根據此代碼對這個example(代碼示例4)

+1

爲什麼不使用一個開關?圍繞annotationType建立一個開關,每個類都有一個案例 – CubeJockey

+2

@Trobbins我相信SONAR在使用開關後仍然會抱怨。 – CKing

+0

@bot啊好的。 – CubeJockey

回答

3

如果反射是一種選擇,你總是可以做這樣的事情

public class Test { 

    @PathParam("path") 
    public Response doSomething() { 
     return null; 
    } 

    public static void main(String[] args) throws Exception { 
     Method method = Test.class.getMethod("doSomething"); 
     Annotation annotation = method.getAnnotations()[0]; 
     System.out.println(getValue(annotation)); 
    } 

    private static String getValue(Annotation annotation) throws Exception { 
     Class<?> type = annotation.annotationType(); 
     if (!ANNOTATIONS.contains(type)) { 
      throw new IllegalArgumentException("..."); 
     } 
     String value = (String) type.getMethod("value").invoke(annotation); 
     return value; 
    } 

    private static final Set<Class<?>> ANNOTATIONS; 

    static { 
     Set<Class<?>> annotations = new HashSet<>(); 
     annotations.add(HeaderParam.class); 
     annotations.add(QueryParam.class); 
     annotations.add(PathParam.class); 
     annotations.add(MatrixParam.class); 
     annotations.add(CookieParam.class); 
     annotations.add(FormParam.class); 
     ANNOTATIONS = Collections.unmodifiableSet(annotations); 
    } 
} 
+0

謝謝,這就是我一直在尋找的東西。只是我不拋出IllegalArgumentException,只需要返回「」 – mid491