Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to block/deny a cast conversion in Java?

Tags:

java

casting

I have the code of a simple game, where an AgentInterface must be implemented in order to create an agent controller for one of the characters in the game. GameState is a class the implements GameStateInterface, and an object that implements this interface can be passed to the agent, so the agent can read and analyze the data from game state, and the agent must return the appropriate action (returned as an int) that the character should take.

This is the AgentInterface that agents must implement:

public interface AgentInterface {
    // the return value specifies the direction of the joystick
    public int action(GameStateInterface gs);
}

Running the game with an agent called MyAgent:

    GameState gs = new GameState();
    AgentInterface agent = new MyAgent();
    while (true) {
        // more code here
        int bestAction = agent.action(gs)
        // more code here
    }        

But, there is some information in GameState that the agent should NOT be able to access, since that would be cheating for the controller. But, doing a cast conversion from GameStateInterface to GameState would allow the agent to access information that is not defined in the GameStateInterface, like this:

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;
    }
}

My question would be, is it possible to block a cast conversion? I know polymorphism is one of the main features of Java and Object-Oriented Programming Languages, but in cases like this I would like to avoid cast conversions.

I know this can be solved in many other ways, but I was curious to know if it is possible to do this.

Thanks in advance.

like image 316
David Robles Avatar asked Dec 07 '09 22:12

David Robles


1 Answers

As far as I know, it's not possible to intercept a typecast and deny it (say, by throwing a ClassCastException).

But instead of trying to deny the typecase, you can simply use the Proxy pattern to control access to the actual GameState object. Just implement a proxy class, which only implements the GameStateInterface and let it forward all method calls to the GameState object. Now, instead of passing the actual GameState object reference to the action method, you pass it wrapped by an instance of your proxy class.

like image 64
Simon Lehmann Avatar answered Nov 07 '22 07:11

Simon Lehmann