سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

While the methods are public, the class itself is private, so those methods are effectively private as they're only accessible from within the containing class. Your IDE appears to be treating them the same as private methods, warning you if you define one that is never called.

P.S. as an aside, there's no such thing as a "static inner class" - the term "inner class" refers to a non-static nested class whose instances can only exist in the context of a particular instance of the container, so a class cannot be both static and inner at the same time.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top