简体   繁体   中英

How can I redirect the System.out.println() of constructor of superclass to System.setOut() of subclass?

There are some multiple System.out.println() in the constructor of the superclass, and I have to redirect them to PrintStream object ps using System.setOut(ps).

for example, if I have a superclass like this:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;

public class SuperClass implements ActionListener{

    public SuperClass(){
        System.out.println("Some message");
    }

    public String toString(){
        return "Some other message";
    }

    @Override
    public void actionPerformed(ActionEvent event)
    {
        System.out.println(toString());
    }
}

and a subclass like this:

import java.io.IOException;
import java.io.PrintStream;

public class SubClass extends SuperClass{

    private PrintStream ps;

    public SubClass(){
        super();

        try {
            ps = new PrintStream("file.txt");
        } catch (IOException e){
            e.getStackTrace();
        }

        System.setOut(ps);
    } 
}

whenever the action is performed (ex. pressing a JFrame Button from superclass), the System.out.println() from actionPerformed() is redirected to PrintStream object, but the System.out.println() from the constructor is not.

Also, how can I redirect the System.out to PrintStream object AND keep the System.out? (ie printing both System.out and PrintStream)

  1. The problem is in constructors order. Shortly when you call SubClass constructor it calls SuperClass first, because you have to init parent first.( When you call subclass constructor, it always call parent constructor first). This question have answer about init order.
  2. To add info for file and console adding logger can fit your aims. You can configure it in several ways. Link If you want to write without logger, just to file and console, take a look for this question

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