Java:返回静态嵌套类
我有一个静态嵌套类,我想通过静态访问器(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
}
}
我知道为什么这不起作用,因为 Columns 是一个类,而不是一个变量,但是,由于其他原因,我需要将列保留为静态类。我什至不确定这是否可行,但只是想问一下是否可行?
谢谢!
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, because 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,如果您的静态嵌套类是公共的,如您的示例所示,我想知道为什么您要创建一个访问器,而您可以直接访问嵌套类。
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:
If columns was not static and you would like to instantiate it from somewhere else it would require an instance of the outer class
With your solution you can do:
您想要返回 class Column 还是 Column 的实例?
对于前者,您可以使用
对于后者,您可以使用
Do you want to return the class Column or an instance of Column ?
For the former, you can use
For the latter, you can use
如果您实际解释如何使用 Columns 类,可能会有所帮助。您是想获取它的实例还是想获取它是什么类?
您可以返回一个
Class
实例,以允许您的调用方法在其上使用newInstance()
:或者您必须将
Columns
修改为某些内容像:但是从你关于“为
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 usenewInstance()
on it:Or you'll have to modify
Columns
into something like:But from one of your comments about "create a superclass for
SomeClass
, which returnsColumns
", this seems to be a design issue. You can't override static methods so inheritance might makes things worse.这意味着您需要返回 Columns 的实例。
怎么样?
或者,如果您一直想要同一个实例,
This means that you need to return an instance of Columns.
How about
or, if you want the same instance all the time