Dec 24

Static methods cannot call non-static methods. An instance of the class is required to call its methods and static methods are not accociated with an instance (they are class methods). To fix it you have a few choices depending on your exact needs.


/**
*  Will not compile
*/

public class StaticReferenceToNonStatic
{
   public static void myMethod()
   {
      // Cannot make a static reference
      // to the non-static method
      myNonStaticMethod(); 
   }

   public void myNonStaticMethod()
   {
   }
}

/**
* you can make your method non-static
*/

public class MyClass
{
   public void myMethod()
   {
      myNonStaticMethod(); 
   }

   public void myNonStaticMethod()
   {
   }
}

/**
*  you can provide an instance of the 
*  class to your static method for it 
*  to access methods from
*/

public class MyClass
{
   public static void myStaticMethod(MyClass o)
   {
      o.myNonStaticMethod(); 
   }

   public void myNonStaticMethod()
   {
   }
}

/**
*  you can make the method static
*/

public class MyClass
{
   public static void myMethod()
   {
      f(); 
   }

   public static void f()
   {
   }
} 

written by objects \\ tags: ,

Dec 22

The java.util.Timer class can be used to schedule code to be executed repeated at a fixed interval. The TimerTask class is used to encapsulate the code to be executed.


Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    public void run()
    {
        // put the code you want to run here
    }
}, initialDelay, interval); 

written by objects \\ tags: , ,

Dec 21

Sometimes you need to store the stack trace from an exception in a String. A common approach is to use the printStackTrace() method to write it to a String which gives it to you in the same format as when you print it to stdout (or whereever)

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String trace = sw.toString();

Another option is to use the stack trace directly to create your string. This allows you to have full control over the format. For example you could use something as simple as the following:

String trace = Arrays.toString(ex.getStackTrace());

written by objects \\ tags: , , , ,