java中对象作用域方法的静态实现
嗨:我有一个定义以下方法的类:
public String abstract getAnimalName();
和一个子类,
class Ralph extends Animal
{
public String getAnimalName(){return "RALPH";}
}
我希望“Ralph”的 getAnimalName 是静态的,因为只有一个,无状态的 拉尔夫名字的版本。
因此,我想静态实现 getAnimalName,同时仍然满足接口。这可能吗?也许,有没有一种方法可以使用依赖注入或 AOP 技术通过在运行时代理静态对象来提供对象实现?
显而易见的解决方案(使用对象作用域方法包装静态方法)对于我的口味来说有点乏味。
Hi : I have a class defining the following method :
public String abstract getAnimalName();
And a subclass
class Ralph extends Animal
{
public String getAnimalName(){return "RALPH";}
}
I want "Ralph"'s getAnimalName to be static, since there is only one, stateless
version of Ralph's name.
Thus, I want to implement the getAnimalName statically, whilst still satisfying the interface. Is this possible ? Maybe, is there a way I can use a dependency injection or AOP technique to provide the object implementation by proxying the static one at run time ?
The obvious solution (of having an object scope method wrap a static method) is a little to boiler-plateish for my tastes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,你能做的就是你最后的建议。
这可能是一个警告,表明设计中存在可疑之处。
Ralph 是一个实例,因此需要遵守
getAnimalName
的约定。Nope, your last suggestion is all you can do.
This might be a warning that something is suspicious in the design.
Ralph is an instance, and as such needs to obey the contract of
getAnimalName
.您最好的做法是:
如果您愿意,您也可以将
NAME
公开。You'll be best doing:
You may also make
NAME
public if you want.设计确实需要经过审查。如果您对架构感到满意,我会将类转换为单例并使用 Ralph.getInstance().getAnimalName()。
也许考虑一下注释?
您可以从 Class 对象中提取注释: http: //docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getAnnotations()
The design needs to be reviewed for sure. If you're happy with the architecture, I would turn the class into a singleton and use Ralph.getInstance().getAnimalName().
Perhaps consider annotations for this?
You can pull annotations off the Class object: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getAnnotations()
为什么不将代码更改为下一种方式:
不仅仅是使用 getAnimalName() 方法。
Why don't you change your code to the next way:
more than use your getAnimalName() method.
实际上并不存在一个方法有多个实例的概念。当您创建多个
Ralph
对象时,它不会添加任何额外的内存。但是,您可能想要创建一个元类型。
There isn't really a concept of more than one instance of a method. It wont add any extra memory when you create multiple
Ralph
objects.You might, however, want to create a meta-type.