Topaz Centuallas
Topaz Centuallas

Reputation: 13

How do I resolve this Unchecked cast warning?

This line gives me the unchecked cast warning

this.gameSocket = (U) game.getGameSocket();

SocketHandler.java:

public class SocketHandler<T extends Game, U extends GameSocket> extends 
Listener
{
    protected T game;
    protected U gameSocket;

    public SocketHandler(T game)
    {
        this.game = game;
        this.gameSocket = (U) game.getGameSocket();
    }
}

Game.java:

public class Game<T extends GameSocket>
{
    protected T gameSocket;

    public T getGameSocket()
    {
        return gameSocket;
    }

    public Game()
    {

    }
}

GameSocket.java:

public class GameSocket<T extends Game>
{
    protected T game;
    protected int port;

    public GameSocket(T game, int port)
    {
        this.game = game;
        this.port = port;
    }
}

I feel as if there is a generic circulation issue here but the code works fine. However, there is probably a better way of doing what I am doing here.

Upvotes: 1

Views: 106

Answers (1)

Jacob G.
Jacob G.

Reputation: 29720

You have a generic loop: the generic type of GameSocket extends Game, but the generic type of Game extends GameSocket!

To fix this, I recommend changing GameSocket's class declaration to:

public class GameSocket<T> {
    ...
}

Then, you can change Game's class declaration to:

public class Game<T extends GameSocket<T>> {
    ...
}

Finally, you can change SocketHandler's class declaration to:

public class SocketHandler<T extends Game<U>, U extends GameSocket<U>> extends Listener {
    ...
}

This makes everything type-safe and the warning is gone.

You can even remove the explicit cast (U) when retrieving game.getGameSocket()

Upvotes: 1

Related Questions