java优化if语句_(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抱怨这种方法的复杂性.

改变它并不容易,因为我们需要在获取其值之前检查注释类型!

注意:陷阱位于Annotation接口上,该接口没有value()方法.

附: :此代码基于此example(代码示例4)

解决方法:

如果反射是一种选择,你总是可以这样做

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> ANNOTATIONS;

static {

Set> 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);

}

}

标签:java,rest,annotations,jax-rs,sonarqube

来源: https://codeday.me/bug/20190628/1317528.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值