我有一个简单的游戏代码,其中AgentInterface必须实现以便为游戏中的其中一个角色创建代理控制器。 GameState是实现GameStateInterface的类,并且实现此接口的对象可以传递给代理,因此代理可以从游戏状态读取和分析数据,并且代理必须返回适当的操作(作为int返回)角色应该采取。是否可以阻止/拒绝Java中的强制转换?
这是AgentInterface代理商必须实现:
public interface AgentInterface {
// the return value specifies the direction of the joystick
public int action(GameStateInterface gs);
}
运行游戏的代理称为MyAgent:
GameState gs = new GameState();
AgentInterface agent = new MyAgent();
while (true) {
// more code here
int bestAction = agent.action(gs)
// more code here
}
但是,有在游戏状态的一些信息,代理不应该能够访问,因为这将是对控制器的欺骗。但是,这样做从GameStateInterface铸造转化为游戏状态将允许代理访问未在GameStateInterface定义的信息,像这样:
public MyAgent implements AgentInterface {
public int action(GameStateInterface gs) {
int nLives = ((GameState) gs).nLivesRemaining; // IS IT POSSIBLE TO DENY/PREVENT THIS CAST??
// Do more stuff here
return BestAction;
}
}
我的问题是,是否有可能阻止铸造转换?我知道多态是Java和面向对象编程语言的主要特性之一,但在这种情况下,我想避免强制转换。
我知道这可以通过许多其他方式解决,但我很想知道是否有可能这样做。
在此先感谢。
这似乎是一个很好的解决方案。 +1 – 2009-12-07 22:59:00
警告 - 确保配置了Java安全性,以便代理(即不可信)代码不能使用Reflection API。有人可以使用反射来访问代理类的私有成员来获取GameState对象。 – 2009-12-08 03:14:10