我有几个接口,它们都有相同的常量-- ID和ROOT。我还有一个方法,我向其中传递一个对象,该对象将是这些接口之一的实现。
如何根据传入的类动态检索常量的值--也就是说,我想做类似以下的事情:
public void indexRootNode(Node node, Class rootNodeClass)
{
indexService.index(node, rootNodeClass.getConstant('ID'),
rootNodeClass.getConstant('ROOT'));
}
在PHP中这很容易,但是在Java中这可能吗?我看到这个问题通过在常量上使用访问器来解决,但是我想直接检索常量。注解在这里也帮不了我。
谢谢
2条答案
按热度按时间piv4azn71#
这可以使用reflection实现(另请参见相应的javadoc)。
也许您还必须将值强制转换为相应的类型。
of1yzvn42#
请阅读约书亚Bloch的Effective Java中的第19章useinterfaces only to defined type(实际上,请阅读整本书)
常量不属于接口!!!常量应该绑定到实现类,而不是接口。
使用非常量方法:
或者使用一个枚举来把东西联系在一起: