Search code examples
javaandroidnio

Casting NIO Channel at Run Time


I have a class that implements 'Runnable' to read data from a data stream. The data comes from a Channel which is stored as a member variable in another of my classes, and I can get an instance of this channel by simply calling the getter getInputChannel(). Now, for my Runnable to read the data from the channel, it needs to know what type of channel it is so that it can use the channel's read method. The channel type may be one of either FileChannel or SocketChannel, and is decided at run time, i.e.,

private class ReadInputStream implements Runnable {

    Thread thread;
    boolean running = true;
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    FileChannel or SocketChannel channel;

    public ReadInputStream() {
        // Need to cast type channel at run time
        Channel ch = getInputChannel();
        this.channel = (FileChannel or SocketChannel) ch;
    }

    public void run() {
        while (running) {
             channel.read(buffer);
             // etc.
        }
    }

}

What is the best way to get the right type of channel so that I can implement its read method in the runnable's run() method?


Solution

  • Both FileChannel and SocketChannel implement ByteChannel which is what declares their read(ByteBuffer) method, so that's the type your getInputChannel() should return.

    Edit Or if you only ever read from the channel, return a ReadableByteChannel as Darkhogg says. Since this is an input channel, this is most likely the case anyway.