简体   繁体   中英

Java: How to create new class object for Reader class from java.io when it has protected constructor

I wanted to create a new class object for java's Reader class, but I can't access the constructor since it is protected.

Reader Class Description

Reader myReader = new Reader(); 

Will not work.

Normally, I would create a new function that class to access that constructor, but since the function is a part of java default library, how do I access it? Thanks for any help.

Reader is an abstract class. You cannot instantiate it, only for the purposes of making a subclass instance.

Did you mean

Reader myReader = new InputStreamReader(in, "UTF-8");

Reader是一个抽象类,因此您必须实例化它的实现,例如BufferedReaderInputStreamReader

As others said, you may create a instance of subclass of Reader , such as BufferedReader .

If you don't want to use subclass of Reader, you may create instance of Reader like below

Reader reader = new Reader() {

        @Override
        public int read(char[] cbuf, int off, int len) throws IOException {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public void close() throws IOException {
            // TODO Auto-generated method stub

        }};

If you check the Reader Java Doc you can see the concrete subclasses of Reader intialyze any one of them based on your requirement. You cannnot instantial Reader as it is abstract

BufferedReader
CharArrayReader
FilterReader
InputStreamReader
PipedReader
StringReader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM