Hide Utility Class Constructor : Utility classes s

2019-03-08 06:53发布

I am getting this warning on Sonar.I want solution to remove this warning on sonar. My class is like this :

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

i want proper solution to remove this warning on sonar.

8条回答
Animai°情兽
2楼-- · 2019-03-08 07:12

I don't know Sonar, but I suspect it's looking for a private constructor:

private FilePathHelper() {
    // No-op; won't be called
}

Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.

(You should also make it final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)

查看更多
神经病院院长
3楼-- · 2019-03-08 07:13

I use an enum with no instances

public enum MyUtils { 
    ; // no instances
    // class is final and the constructor is private

    public static int myUtilityMethod(int x) {
        return x * x;
    }
}

you can call this using

int y = MyUtils.myUtilityMethod(5); // returns 25.
查看更多
你好瞎i
4楼-- · 2019-03-08 07:16

Best practice is to throw an error if the class is constructed.

Example:

/**
 * 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.");
}
查看更多
虎瘦雄心在
5楼-- · 2019-03-08 07:16

Add private constructor:

private FilePathHelper(){
    super();
}
查看更多
相关推荐>>
6楼-- · 2019-03-08 07:16

SonarQube documentation recommends adding static keyword to the class declaration.

That is, change public class FilePathHelper to public static class FilePathHelper.

Alternatively you can add a private or protected constructor.

public class FilePathHelper
{
    // private or protected constructor
    // because all public fields and methods are static
    private FilePathHelper() {
    }
}
查看更多
Ridiculous、
7楼-- · 2019-03-08 07:18
public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

This prevents the default parameter-less constructor from being used elsewhere in your code.

查看更多
登录 后发表回答