/home/wpollock1/public_html/AJava/ReflectionDemo.java

// Demo of simple reflection.
// Note that all objects automatically have a "toString" method,
// and using "System.out.println( ... + obj + ... );" will use it.
//
// Written 10/2010 by Wayne Pollock, Tampa Florida USA.
// Updated 2/2018 by WP: Fixed Generics warning on line 21, by adding "<?>",
//                       and the deprecation of NewInstance.

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Scanner;

public class ReflectionDemo
{
   public static void main ( String [] args ) throws Exception
   {
      Scanner in = new Scanner ( System.in );

      System.out.print( "Enter a class name (e.g., java.util.Date): " );
      String name = in.next();

      Class<?> cl = Class.forName( name );  // Load some class into the JVM.

      System.out.println( name + ".class: " + cl.getName() );

      Object obj = cl.getDeclaredConstructor().newInstance();  // Uses no-arg constructor.
      System.out.println( "obj.toString(): " + obj );

      System.out.println( "Enter one of the following \"no-arg\" method "
        + "names for " + cl + ":\n" );

      Method[] methods = cl.getMethods();
      for ( Method m : methods )
      {
         if ( m.getParameterTypes().length == 0 )
            System.out.println( "\t" + m );  // Print methods that take no args
      }

      System.out.print( "\nEnter method name (e.g., \"toString\"): " );
      String methodName = in.next();

      @SuppressWarnings("unchecked") // Turn off warning about unchecked types.
      Method method = cl.getMethod( methodName );
      Object result = method.invoke( obj );
      System.out.println( "method " + cl.getName() + "." + method.getName()
         + " returned: " + result );

//    ---------------------------------------------------------------

      // Shows use of "class" final field (same as obj.getClass()):
      cl = Date.class;
      System.out.println( "\n\nDate.class: " + cl.getName() );

      /* Shows internal mangled names for "internal" types, such as
       * primitives and arrays.  Here's a list of these:
       *    B (byte)
       *    C (char)
       *    D (double)
       *    F (float)
       *    I (int)
       *    J (long)
       *    S (short)
       *    Z (boolean)
       *    Lclassname;  (object types)
       *    [type (array of type)
       *    V (void)
       */

      obj = new Double[10];  // Array of Double objects
      cl = obj.getClass();
      System.out.println( "Array of Double: " + cl.getName() );

      obj = new double[10];  // array of double primitives
      cl = obj.getClass();
      System.out.println( "Array of double: " + cl.getName() );
   }
}