我在没有真正打印概念的嵌入式平台上使用Java 1.6,所以我正在尝试实现自己的。我正在尝试提供自己的类实现,与Oracle提供的用于在Unix或Windows平台上进行打印的内容并行,但我遇到了问题。 java.awt.print.PrinterJob类用于获取特定于平台的PrinterJob实例。在Windows上,PrinterJob.getPrinterJob()返回sun.print.Win32PrintJob的实例,该实例是在PrinterJob.getPrinterJob()中使用系统属性java.awt.printerjob上的反射创建的。一旦有了PrinterJob的实例,就可以使用其他API方法进行打印,这在本网站上已经多次回答过。我尝试使用-Djava.awt.printerjob = initialization.CustomPrinterJob运行,这是我的PrinterJob实现,但系统属性似乎在虚拟机启动时重置,所以我在我的代码中使用System.setProperty(“java。 awt.printerjob“,”initialization.CustomPrinterJob“)但这样做会导致PrinterJob.getPrinterJob()产生ClassNotFoundException,我希望它能使用我的代码。我可以使用反射创建该对象的实例,所以我不确定为什么java.awt.print.PrinterJob.getPrinterJob方法不能。我已经在下面发布了我的代码,如果有人可以提供帮助或有任何想法,我会非常感激。
MyPrinterJobExample.java:
package initialization;
import java.awt.AWTError;
import java.awt.print.PrinterJob;
public class MyPrinterJobExample {
// Copied from PrinterJob.getPrinterJob()
public static PrinterJob getPrinterJob() {
// Copied and Pasted the body of PrinterJob.getPrinterJob() Here
}
/**
* The Entry Point into this Application
* @param args the Command Line Arguments, which should be none
*/
public static void main(String[] args) {
try {
// Override some System Properties
System.setProperty("java.awt.printerjob", "initialization.CustomPrinterJob");
System.out.println("java.awt.printerjob: " + System.getProperty("java.awt.printerjob", null));
// Direct Creation (works)
PrinterJob p = new CustomPrinterJob();
// Reflection Creation (works)
PrinterJob p2 = (PrinterJob)Class.forName("initialization.CustomPrinterJob").newInstance();
// Copied from PrinterJob.getPrinterJob (works?)
PrinterJob p3 = MyPrinterJobExample.getPrinterJob();
// PrinterJob.getPrinterJob (fails)
PrinterJob p4 = PrinterJob.getPrinterJob();
} catch(Throwable t) {
t.printStackTrace(System.err);
}
}
}
CustomPrinterJob.java:
package initialization;
public class CustomPrinterJob extends PrinterJob {
// Assume the Necessary Abstract Functions are Implemented
}
输出:
java.awt.printerjob: initialization.CustomPrinterJob
Creating CustomPrinterJob
Creating CustomPrinterJob
Creating CustomPrinterJob
java.awt.AWTError: PrinterJob not found: initialization.CustomPrinterJob
at java.awt.print.PrinterJob$1.run(PrinterJob.java:66)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.print.PrinterJob.getPrinterJob(PrinterJob.java:59)
at initialization.MyPrinterJobExample.main(MyPrinterJobExample.java:52)