Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is java.io.FileDescriptor's constructor public?

Tags:

java

JavaDoc for java.io.FileDescriptor.FileDescriptor() says:

Constructs an (invalid) FileDescriptor object.

If there is no purpose for the constructor, why is it's access level not declared to be package-private?

like image 304
Pacerier Avatar asked Oct 08 '22 05:10

Pacerier


1 Answers

This constructor is public because it is used outside of java.io.

Classes using new FileDescriptor() in JRE 7u4 Linux x86:

java.io.FileInputStream
java.io.FileOutputStream
java.io.RandomAccessFile

java.lang.UNIXProcess
java.net.AbstractPlainDatagramSocketImpl
java.net.AbstractPlainSocketImpl
java.net.ServerSocket

sun.net.sdp.SdpSupport
sun.nio.ch.FileChannelImpl
sun.nio.ch.FileDispatcherImpl
sun.nio.ch.IOUtil
sun.nio.ch.PipeImpl
sun.nio.ch.SctpServerChannelImpl
sun.nio.ch.ServerSocketChannelImpl
sun.nio.ch.UnixAsynchronousServerSocketChannelImpl
sun.nio.fs.UnixChannelFactory

There is a sun.misc.SharedSecrets method that allows the programmer to change the state of a FileDescriptor to a valid one (this snippet found in java.io.FileDescriptor):

  static {
        sun.misc.SharedSecrets.setJavaIOFileDescriptorAccess(
            new sun.misc.JavaIOFileDescriptorAccess() {
                public void set(FileDescriptor obj, int fd) {
                    obj.fd = fd;
                }

                public int get(FileDescriptor obj) {
                    return obj.fd;
                }

                public void setHandle(FileDescriptor obj, long handle) {
                    obj.handle = handle;
                }

                public long getHandle(FileDescriptor obj) {
                    return obj.handle;
                }
            }
        );
    }

This means that any code that can access SharedSecrets (I.E. the JRE itself) can also create its own valid FileDescriptor, and should therefore be allowed to access FileDescriptor(). However, there is no way to restrict the access of a constructor to only JRE classes, so it is public.

like image 84
Jeffrey Avatar answered Oct 12 '22 12:10

Jeffrey