0

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.

4

5 回答 5

4

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.

于 2012-01-04T21:39:09.587 回答
2

你最好这样做:

class Ralph extends Animal { 

    private static final String NAME = "RALPH";

    public String getAnimalName(){return NAME;} 
} 

如果你愿意,你也可以NAME公开。

于 2012-01-04T21:42:05.623 回答
1

设计确实需要进行审查。如果您对架构感到满意,我会将类变成单例并使用 Ralph.getInstance().getAnimalName()。

也许考虑为此添加注释?

@Name("RALPH")
class Ralph extends Animal
{}

您可以从 Class 对象中提取注释:http: //docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getAnnotations ()

于 2012-01-04T21:45:57.290 回答
0

实际上并没有一个方法的多个实例的概念。Ralph当您创建多个对象时,它不会添加任何额外的内存。

但是,您可能想要创建一个元类型。

于 2012-01-04T23:00:35.273 回答
0

为什么不将代码更改为下一种方式:

class Ralph extends Animal
{
    public static String NAME = "RALPH";
}

class Animal {
    public static String NAME;

}

不仅仅是使用您的getAnimalName()方法。

于 2012-01-04T21:49:39.363 回答