Oom*_*ity 85 java constructor sonarqube
我在Sonar上收到了这个警告.我想要解决方法在声纳上删除此警告.我的班级是这样的:
public class FilePathHelper {
private static String resourcesPath;
public static String getFilePath(HttpServletRequest request) {
if(resourcesPath == null) {
String serverpath=request.getSession().getServletContext().getRealPath("");
resourcesPath = serverpath + "/WEB-INF/classes/";
}
return resourcesPath;
}
}
Run Code Online (Sandbox Code Playgroud)
我想要适当的解决方案来消除声纳上的这个警告.
Rof*_*ion 160
如果这个类只是一个实用程序类,你应该使类最终并定义一个私有构造函数:
public final class FilePathHelper {
private FilePathHelper() {
//not called
}
}
Run Code Online (Sandbox Code Playgroud)
这可以防止在代码中的其他位置使用默认的无参数构造函数.此外,您可以使类最终,以便它不能在子类中扩展,这是实用程序类的最佳实践.由于您只声明了一个私有构造函数,因此其他类无论如何都无法扩展它,但将该类标记为final是最佳实践.
Jon*_*eet 18
我不知道Sonar,但我怀疑它正在寻找私有构造函数:
private FilePathHelper() {
// No-op; won't be called
}
Run Code Online (Sandbox Code Playgroud)
否则,Java编译器将提供一个您真正不需要的公共无参数构造函数.
(你也应该把它作为最终的,尽管其他类无论如何都无法扩展它,因为它只有一个私有的构造函数.)
Pet*_*rey 11
我使用没有实例的枚举
public enum MyUtils {
; // no instances
// class is final and the constructor is private
public static int myUtilityMethod(int x) {
return x * x;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以用这个来打电话
int y = MyUtils.myUtilityMethod(5); // returns 25.
Run Code Online (Sandbox Code Playgroud)
最佳做法是在构造类时抛出错误.
例:
/**
* The Class FooUtilityService.
*/
final class FooUtilityService{
/**
* Instantiates a new FooUtilityService. Private to prevent instantiation
*/
private FooUtilityService() {
// Throw an exception if this ever *is* called
throw new AssertionError("Instantiating utility class.");
}
Run Code Online (Sandbox Code Playgroud)
小智 9
您可以只使用 Lombok 注释来避免不必要的初始化。
@NoArgsConstructor与AccessLevel.PRIVATE如下一起使用:
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FilePathHelper {
// your code
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107108 次 |
| 最近记录: |