gpt4 book ai didi

java - (Java)if 语句优化

转载 作者:搜寻专家 更新时间:2023-11-01 03:03:43 25 4
gpt4 key购买 nike

需要优化这段代码:

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 接口(interface)上。

附言: 此代码基于此 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<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);
}
}

关于java - (Java)if 语句优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29848805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com