Invoking Methods of Class Instances

This section provides a tutorial example on how to reflect class methods as Method instances and invoke them directly.

Once a class is loaded as a Class instance, you can reflect its methods as Method instances and invoke them directly like this:

   ClassLoader l = ClassLoader.getSystemClassLoader();
   Class c<?> = l.loadClass(className);
   // Object o = c.newInstance(); // deprecated
   Object o = c.getDeclaredConstructor().newInstance();
   Method m = c.getMethod(methodName, parameterTypes);
   m.invoke(o, args);

Here is tutorial example program showing you how to invoke a method reflected as a Method instance:

/* ClassMethodReflection.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.lang.reflect.*;
class ClassMethodReflection {
   static java.io.PrintStream out = System.out;
   public static void main(String[] a) {
      try {
         // Loading the class and creating an object
         ClassLoader l = ClassLoader.getSystemClassLoader();
         Class<?> c = l.loadClass("java.util.Random");
         Object o = c.getDeclaredConstructor().newInstance();
         Method m = c.getMethod("nextInt", int.class);

         // Invoking the method: o.nextInt(100)
         Object r = m.invoke(o, 100);
         out.println("Random number between 0 and 99: "+r);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

When executed, I got this result:

herong> java ClassMethodReflection
Random number between 0 and 99: 66

herong> java ClassMethodReflection
Random number between 0 and 99: 23

herong> java ClassMethodReflection
Random number between 0 and 99: 47

The method o.nextInt(100) was invoked correctly.

Table of Contents

 About This Book

 JVM (Java Virtual Machine) Specification

 Java HotSpot VM - JVM by Oracle/Sun

 java.lang.Runtime Class - The JVM Instance

 java.lang.System Class - The Operating System

 ClassLoader Class - Class Loaders

Class Class - Class Reflections

 What Is java.lang.Class Class

 forName() Method - Loading Classes

 Class Reflection and Introspection

 Array Class Introspection

Invoking Methods of Class Instances

 JVM Runtime Data Areas

 JVM Stack, Frame and Stack Overflow

 Thread Testing Program and Result

 CPU Impact of Multi-Thread Applications

 I/O Impact of Multi-Thread Applications

 CDS (Class Data Sharing)

 Micro Benchmark Runner and JVM Options

 Micro Benchmark Tests on "int" Operations

 Micro Benchmark Tests on "long" Operations

 Micro Benchmark Tests in JIT Compilation Mode

 Micro Benchmark Tests on "float" and "double" Operations

 OpenJ9 by Eclipse Foundation

 JRockit JVM 28.2.7 by Oracle Corporation

 Archived Tutorials

 References

 Full Version in PDF/EPUB