⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 construct.java

📁 程序练习中包括书中实例程序代码和练习中要用到的代码,是压缩文件
💻 JAVA
字号:
package examples.rtti;

import java.lang.reflect.*;

/** A class defined to demonstrate the Reflection API
  */
class FirstType {

   private String name;

   public FirstType( String name ) {
      this.name = name;
   }

   public FirstType() {
      this.name = "DefaultFirst";
   }

   public String toString() {
      return ( "A FirstType object named " + name );   
   }
}   
 
/** A class defined to demonstrate the Reflection API
  */
class SecondType {
   
   // explicit constructor needed for reflection API
   public SecondType() {
      // intentionally left empty
   }
      
   public String toString() {
      return ( "A SecondType object" );   
   }  
}

/** A class used to show how the Reflection API can
  * be used to construct objects
  */
public class Construct {

   /** Test method for the class
     * @param args the class name to be constructed
     *    followed by any constructor arguments
     */
   public static void main( String [] args ) {
      if ( args.length == 0 ) {
          System.out.println( " usage: Construct"
                              + " classname"
                              + " [ctor_arg]" );
          return;
      }

      // get the class object for the specified class
      Class classObj = null;
      try {
         classObj = Class.forName( args[0] );
      } catch ( ClassNotFoundException ex ) {
         System.err.println( " Unknown class "
                             + args[0] );
         return;
      }

      // get constructor for class
      Constructor ctor = null;
      Class[] ctorTypes = new Class[args.length-1]; 
      for ( int i=0; i < args.length-1; i ++ ) {
          ctorTypes[i] = java.lang.String.class;
      }
      try {
         ctor = classObj.getConstructor( ctorTypes );
      } catch ( NoSuchMethodException ex ) {
         String msg = "No constructor: ";
         msg += classObj.getName() + "(";
         for ( int i=0; i < ctorTypes.length; i++ ) {
            msg += ctorTypes[i].getName();
            if ( i < ctorTypes.length-1 ) {
               msg += ", ";
            }
         }
         msg += ")";         
         System.err.println( msg );
         return;
      }

      // build up the array of arguments
      // for the constructor from the
      // commmand line arguments
      String[] ctorArgs
         = new String[ctorTypes.length];
      System.arraycopy( args, 1, ctorArgs, 0,
                        ctorTypes.length );
      // call the constructor
      Object obj = null;
      try {
         obj = ctor.newInstance( ctorArgs );
      } catch ( Exception ex ) {
         ex.printStackTrace();
         return;
      }

      // print the object created
      System.out.println( obj );
   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -