I'm trying to make an EasyPrint class that allows you to print to the console with just print(), println(), and printf(), instead of having to do System.out or out. It also lets you set it to use a different PrintStream or a PrintWriter. However, when I test it, I get this error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable code
at easyprint.EasyPrint.print(EasyPrint.java:1)
at tests.TestEasyPrint.main(TestEasyPrint.java:15)
C:\Users\myUsername\AppData\Local\NetBeans\Cache\17\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\myUsername\AppData\Local\NetBeans\Cache\17\executor-snippets\run.xml:68: Java returned: 1
BUILD FAILED (total time: 0 seconds)
As you can see, it doesn't provide any information about the problem besides the run.xml stuff, which I don't understand.
Here's a shortened version of the class and the test that has the same problem:
import java.io.*;
public class ShortEasyPrint {
private static Object output = System.out;
public static void setOutput(PrintStream output) {
ShortEasyPrint.output = output;
}
public static void setOutput(PrintWriter output) {
ShortEasyPrint.output = output;
}
public static void print(String s) {
if (output instanceof PrintStream printStream)
printStream.print(s);
else if (output instanceof PrintWriter printWriter)
printWriter.print(s);
}
public static void main(String[] args) {
print("Test");
}
}
I've tried putting the test program in the same package, and the same class too (like in the example), and it still doesn't work (of course, even if they did work there, I wouldn't be able to use the class for other programs). I put the run.xml in pastebin, in case it helps: https://pastebin.com/zMYe78SN
Does anyone know what's wrong?
Although I can't reproduce your problem, I think it is occurring because of a bug in NetBeans. See Uncompilable code exception with Compile on Save #5260.
That bug report cites using instanceof
pattern matching as a trigger for that "Uncompilable code" error, and also using the "Compile on save" build option. So here are a couple of changes you can make to avoid the issue:
[1] Change your print()
method to not use the instanceof
pattern matching syntax:
public static void print(String s) {
if (ShortEasyPrint.output instanceof PrintStream) {
PrintStream printStream = (PrintStream)output;
printStream.print(s);
} else if (ShortEasyPrint.output instanceof PrintWriter) {
PrintWriter printWriter = (PrintWriter)output;
printWriter.print(s);
}
}
(There are other ways to implement that logic, but that is irrelevant with respect to your problem.)
[2] Uncheck {project} > Properties > Build > Compiling > Compile on Save if it is currently checked.
Notes:
formatterPatternSwitch()
example.