Search code examples
javastatic-methodsinner-classesstatic-classprivate-class

Is the following "private static inner class" implementation correct?


I have made a public "Utils" class, where I put some general static methods that are frequently used. Inside that Utils class, I have created a private static inner class, of some "tool" that Utils supplies. (That tools is some kind of a parser for my needs). One of the methods in Utils, returns a new instance of that parser, and everything works ok. The "problem" is that I am getting warnings, for every public method inside the parser, that is not called from the containing Utils class.

This is the skeleton of how it looks:

public class Utils 
{
    public static Parser(String[] msgs) throws Exception
    {
        return Parser.create(msgs);
    }

    private static class Parser
    {       
        /** fields... **/

        private Parser()
        {}

        public static Parser create(String[] msgs) throws Exception
        {
            Parser parser = new Parser();
            setupParser(msgs);
            return parser;
        }

        private static void setupParser(String[] msgs) throws Exception
            { // do stuff 
            }

        public boolean someInnerMethod(String key)
            {
            // do stuff
            }
     }
}

The method someInnerMethod raises the warning:

The method someInnerMethod(String) from the type Utils.Parser is never used locally

Am I doing something wrong? Is there a better way of doing what I have done here? I generally want the Parser not to be accessible from the outside, yet getting it could be possible using a static method (I don't want to instantiate a Utils class every time I need it's methods)

Thanks in advance.


Solution

  • It's not correct. You won't be able to use your class - You cannot use the return value in your static factory method (right now it won't compile, but I guess the return value is supposed to be Parser). The visibility of the return value makes it inaccessible for anyone using your factory method.

    A workaround would be to factor out a public interface that the inner class implements and use this as the return value for your factory method.