Please click here if you are not redirected within a few seconds.
Java Notes › shanebow.com
Java Notes

Java™ SE 8 API

Snippets

Variable Reference to a Method

You can hold a reference to any method in a variable — use the :: 'operator' to grab a method reference from an object.

See:

Example:

import java.util.function.Consumer;

public class Main {

    public static void main(String[] args) {
        final Consumer<Integer> simpleReference = Main::someMethod;
        simpleReference.accept(1);

        final Consumer<Integer> another = i -> System.out.println(i);
        another.accept(2);
    }

    private static void someMethod(int value) {
        System.out.println(value);
    }
}

Reflection

Reflection allows an executing Java program to reflect upon or inspect itself, and manipulate the code.

Example: A class that determines the names of all its methods and displays them:

import java.lang.reflect.*;


   public class DumpMethods {
      public static void main(String args[])
      {
         try {
            Class c = Class.forName(args[0]);
            Method m[] = c.getDeclaredMethods();
            for (int i = 0; i < m.length; i++)
            System.out.println(m[i].toString());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }