开发者

Java: return static nested class

I have a static nested class, which I would like to return via a static accessor (getter).

public class SomeClass
{
    public static class Columns<CC>
    {
        ...

        public static int length = 5;
    }

    public static Columns<?> getColumnEnumerator()
    {
        int x = Columns.length; //no problems

        return Columns; //compiler error
        //cannot find symbol: variable Columns location: blah.blah.SomeClass
    }
}

I know why this doesn't work, beca开发者_运维百科use Columns is a class, and not a variable, however, for other reasons, I need to keep columns as a static class. I am not even sure if this doable, but just wanna ask if there was?

Thanks!


Well, if your static nested class is public, as in your example, I'm wondering why you want to create an accessor while you can directly access the nested class.


You still need to instantiate the Class, like:

 return new Columns();

If columns was not static and you would like to instantiate it from somewhere else it would require an instance of the outer class

return new SomeClass().new Columns();

With your solution you can do:

return new SomeClass.Columns();


Do you want to return the class Column or an instance of Column ?

For the former, you can use

return SomeClass.Columns.class; // SomeClass.Columns can also be accessed directly,
                                // since it is public.

For the latter, you can use

return new SomeClass.Columns();


It might help if you actually explain how your Columns class is to be used. Are you trying to get an instance of it or are you trying to get what class it is?

You can return a Class instance to allow your calling method to use newInstance() on it:

public static Class<Columns> getColumnEnumerator()
{
    int x = Columns.length;

    return Columns.class;
}

Or you'll have to modify Columns into something like:

public class SomeClass
{
    public static class Columns<CC>
    {
       public final int LENGTH = 5;  // changed to a final, or create an accessor

       ...

       private Columns() { ... }  // private constructor
    }

    public static Columns<?> getColumnEnumerator()
    {
        Columns columns = new Columns();  // only SomeClass can instantiate this
        int x = columns.LENGTH;

        return columns;
    }
}

But from one of your comments about "create a superclass for SomeClass, which returns Columns", this seems to be a design issue. You can't override static methods so inheritance might makes things worse.


 public static Columns<?> getColumnEnumerator()

This means that you need to return an instance of Columns.

How about

 return new Columns();

or, if you want the same instance all the time

 return Columns.privateSingletonInstance;  // from a static field
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜