Oct 23

One thing reflection allows you to do is call a method dynamically at runtime. The following example shows how this can be achieved

// Get the Class instance of the object we want to call method on

Class clazz = o.getClass();

// Get the method we want to call
// For this example we'll call a method with this signature
// Double doSomething(String name, Integer[] args)

Method method = clazz.getMethod("doSomething", new String{ String.class, Integer[].class);

// Now invoke the method

Double result = (Double) method.invoke(o, new Object[] {
   "Test", 
   new Integer[] { new Integer(1), new Integer(3)});

written by objects \\ tags: , ,

Mar 14

Reflection allows you to find all the methods of a class using the Class class and it’s getMethods() methods. Clearest way to explain is with an example.

String className = "java.lang.String";
Class clazz = Class.forName(className);
Method[] methods = clazz.getMethods();
for (Method method : methods)
{
	String methodName = method.getName();
	System.out.println(methodName);
}

written by objects \\ tags: , ,

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: ,