Java Reflection and Methods.

How to handle the methods in a class with the Java Reflection.

There are several methods to fetch methods of a class.

The getMethods() method

  • To find the public methods of a class, you must invoke the getMethods() method on the Class object.
  • The getMethods() method will return an array of public Method objects which also includes those inherited from superclasses as well.
    Class rectangleClassObject = Rectangle.class;
    Method [] method= rectangleClassObject.getMethods();

The getMethod(...) method

  • To get a specific public Method use the getMethod(String name, Class<?>... parameterTypes) method on the Class object.
    Class rectangleClassObject = Rectangle.class;
    Class parms = new Class[0];
    Method method= rectangleClassObject.getMethod("getName",parms);
    //this will get the getName methode of the Rectangle class without parameters.
    For none public methods the getMethod(String name, Class<?>... parameterTypes) throws a NotSuchFieldException, which must be caught or declared.

The getDeclaredMethods() method

  • The getDeclaredMethods() method on the Class object ignores inherited methods (in superclasses), but returns all public, protected and private methods in an array.
    Class rectangleClassObject = Rectangle.class;
    Method [] method= rectangleClassObject.getDeclaredMethods();

How do we execute a method on an object of a class.

The invoke(...) method

  • You can invoke a method by providing an object and parameter array to the invoke() method.
    Rectangle rect = new Rectangle();
    Class parms = new Class[0]; // The methode has not parameter
    Method method= rect.getMethod("getName",parms);
    // this will get the getName methode of the Rectangle class without parameters.
    Object values = new Object[0]; // It is - not any parameter values
    String retValue=(String)method.invoke(rect,values);

How do we find the return type of a method on an object of a class.

The getReturnType() method

  • The getReturnType() method on the Method object returns a Class object, which defines the return for the method.

How do we find the modifiers of a method on an object of a class.

The getModifiers() method

  • The getModifiers() method on the Method object returns an int, which defines the modifiers for the method. In the Modifier class you will find several static final fields and methods for decoding the modifier value.

An example where we use the methods mention above.

  • Below is an example that shows how to use these opportunities to investigate all the methods in a class:
    First, we need a class to our analysis:
    package listmethods;
    
    import java.awt.Color;
    
    public class Rectangle   {
      public String name;
      protected int length;
      protected int width;
      private Color color;
      public Rectangle() {
        this("undefined", 10, 10, Color.white);
      }
      @Override
      public String toString() {
        return " Name: " + name+", width: " +
                width + ", length: " + length + ", color: " + color;
      }
      public Rectangle(String name, int width, int length, Color color) {
        this.name=name;
        this.length = length;
        this.width = width;
        this.color = color;
      }
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
      public int getLength() {
        return length;
      }
      public void setLength(int length) {
        this.length = length;
      }
      public int getWidth() {
        return width;
      }
      public void setWidth(int width) {
        this.width = width;
      }
      public Color getColor() {
        return color;
      }
      public void setColor(Color color) {
        this.color = color;
      }
    }
    Here are the main class that creates an object of the Rectangle class, which we examine in terms of methods:
    package listmethods;
    
    import java.awt.Color;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    
    public class Main {
    
      public static void main(String[] args) throws NoSuchMethodException,
              IllegalAccessException, IllegalArgumentException,
              InvocationTargetException {
        Rectangle rect = new Rectangle("football ground", 60, 100, Color.green);
        System.out.println("Object before any changes:\n" + rect);
        Class rectangleClassObject = rect.getClass();
        System.out.println("\nFinding all declared methods "
                           +"and its return type and parameter types:");
        Method[] methods = rectangleClassObject.getDeclaredMethods();
        for (Method method : methods) {
          Class retType = method.getReturnType();
          int mod = method.getModifiers();
          System.out.print(Modifier.toString(mod) + " "+retType.getName()
                           + " " + method.getName() + "(");
          Class[] paratypes = method.getParameterTypes();
          String comma = "";
          for (Class paratype : paratypes) {
            System.out.print(comma + paratype.getName());
            comma = ",";
          }
          System.out.println(")");
        }
        System.out.println("\nFinding all public methods"+
                           "and its return type and parameter types:");
        Method[] amethods = rectangleClassObject.getMethods();
        for (Method method : amethods) {
          Class retType = method.getReturnType();
          int mod = method.getModifiers();
          System.out.print(Modifier.toString(mod) + " "+retType.getName()
                           + " " + method.getName() + "(");
          Class[] paratypes = method.getParameterTypes();
          String comma = "";
          for (Class paratype : paratypes) {
            System.out.print(comma + paratype.getName());
            comma = ",";
          }
          System.out.println(")");
        }
    
        System.out.println("\nFinding a public method and invoke it:");
        Class [] params = {Color.class};
        Method method = rectangleClassObject.getMethod("setColor",params);
        Object [] values = {Color.blue};
        method.invoke(rect, values);
    
        System.out.println("\nObject after any changes:\n" + rect);
    
      }
    }
    The result of this is:
    Object before any changes:
     Name: football ground, width: 60, length: 100, color: java.awt.Color[r=0,g=255,b=0]
    
    Finding all declared methods and its return type and parameter types:
    public int getLength()
    public java.lang.String toString()
    public java.lang.String getName()
    public void setName(java.lang.String)
    public void setLength(int)
    public int getWidth()
    public void setWidth(int)
    public java.awt.Color getColor()
    public void setColor(java.awt.Color)
    
    Finding all public methodsand its return type and parameter types:
    public int getLength()
    public java.lang.String toString()
    public java.lang.String getName()
    public void setName(java.lang.String)
    public void setLength(int)
    public int getWidth()
    public void setWidth(int)
    public java.awt.Color getColor()
    public void setColor(java.awt.Color)
    public final void wait()
    public final void wait(long,int)
    public final native void wait(long)
    public native int hashCode()
    public final native java.lang.Class getClass()
    public boolean equals(java.lang.Object)
    public final native void notify()
    public final native void notifyAll()
    
    Finding a public method and invoke it:
    
    Object after any changes:
     Name: football ground, width: 60, length: 100, color: java.awt.Color[r=0,g=0,b=255]
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.