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 10

Static constants can be used in your Spring wiring using either FieldRetrievingFactoryBean, or the newer util schema.

(2.0+) util schema


<bean id="myBean" class="au.com.objects.MyBean">
   <property name="dayOfWeek">
      <util:constant static-field="java.util.Calendar.MONDAY"/>
   </property>
</bean>

(Pre-2.0) FieldRetrievingFactoryBean


<bean id="myBean" class="au.com.objects.MyBean">
   <property name="dayOfWeek">
      <bean id="java.util.Calendar.MONDAY"
         class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>
   </property>
</bean>

written by objects \\ tags: , , , ,

Sep 25

Static methods cannot access non-static member variables. An instance of the class is required to access its member variable and static methods are not associated 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
{
   protected int x;

   public static void myMethod()
   {
      // Cannot make a static reference
      // to the non-static field
      x = 6; 
   }
}

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

public class MyClass
{
   protected int x;

   public void myMethod()
   {
      x = 6;
   }
}

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

public class MyClass
{
   protected int x;

   public static void myMethod(MyClass myClass)
   {
      myClass.x = 6;
   }
}

/**
*  you can make the member variable static
*/

public class MyClass
{
   protected static int x;

   public static void myMethod()
   {
      x = 6;
   }
} 

written by objects \\ tags: