I believe I am able to use the fully qualified name instead of an import, if I am wrong please correct me (this is my first post here.) This could probably be done using reflection as well.
Edit: here's a reflective solution using only java.lang.reflect.*
:
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Test {
public static void main(String... args) {
System.setOut(null);
System.setErr(null);
try {
Class<?> psClass = Class.forName("java.io.PrintStream");
Class<?> fsClass = Class.forName("java.io.FileOutputStream");
Class<?> osClass = Class.forName("java.io.OutputStream");
Class<?> fdClass = Class.forName("java.io.FileDescriptor");
Class<System> sClass = System.class;
Constructor psCtor = psClass.getConstructor(osClass);
Constructor fsCtor = fsClass.getConstructor(fdClass);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
Object sout = psCtor.newInstance(fsCtor.newInstance(fdClass.getDeclaredField("out").get(null)));
Field outField = sClass.getDeclaredField("out");
modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL);
outField.set(null, sout);
Object serr = psCtor.newInstance(fsCtor.newInstance(fdClass.getDeclaredField("err").get(null)));
Field errField = sClass.getDeclaredField("err");
modifiersField.setInt(errField, outField.getModifiers() & ~Modifier.FINAL);
errField.set(null, serr);
System.out.println("This");
System.err.println("works");
} catch (Exception ignore) {
}
}
}