new operator in static context - how to make it work
pdftest.java:57: non-static variable this cannot be referenced from a static context
PageNumberer pn = new PageNumberer();
Is it basically that I can't use the new operator in my main function because main functions have to be static in java? What's the deal here?
I had this app working as a Java SERVLET, so all i had to do to port it over was replace the doGet method with main and remove all references to servlet specific stuff, etc. Had to make all my methods static too so main could call them, but that's all fixed. And now the thing that makes it not compile is the new operator!?!?
publicclass pdftest
{
....//private static members
/* subClass to handle page numbering of pdf */
class PageNumbererextends PdfPageEventHelper
{
....
}
publicstaticvoid main(String[] args)
{
....
PageNumberer pn =new PageNumberer();
....
}
....//other methods, had to make them all static which was annoying
}
[1543 byte] By [
staticja] at [2007-10-3 9:28:11]

Well, the following change got it to compile: I mad this class static and a package at the top.
package test;
....
static class PageNumberer extends PdfPageEventHelper
{
....
}
BUT now java test.pdftest
results in
Exception in thread "main" java.lang.NoClassDefFoundError: test/pdftest
Your PageNumberer class is a non-static inner class. That means it implicitly has a reference to an instance of the outer class. If you are not using any of the instance method or fields of pdftest, then declare PageNumberer as a static class, i.e.
static class PageNumberer
A static inner class is essentially the same as a normal class except in the sense that it has a more qualified name and slightly different rules for member access.
> pdftest.java:57: non-static variable this cannot be
> referenced from a static context
> PageNumberer pn = new
> PageNumberer();
>
>
> Is it basically that I can't use the new operator in
> my main function because main functions have to be
> static in java? What's the deal here?
>
> I had this app working as a Java SERVLET, so all i
> had to do to port it over was replace the doGet
> method with main and remove all references to servlet
> specific stuff, etc. Had to make all my methods
> static too so main could call them, but that's all
> fixed. And now the thing that makes it not compile is
> the new operator!?!?
>
>
> public class pdftest
> {
> ....//private static members
>
> /* subClass to handle page numbering of pdf */
> class PageNumberer extends PdfPageEventHelper
> {
> ....
> }
>
> public static void main(String[] args)
> {
> ....
> PageNumberer pn = new PageNumberer();
> ....
> }
> ....//other methods, had to make them all static
> c which was annoying
> }
static class PageNumberer