Make up a compilable version of a given Sun or other API : 类 « 映射 « Java

En
Java
1. 图形用户界面
2. 三维图形动画
3. 高级图形
4. 蚂蚁编译
5. Apache类库
6. 统计图
7. 
8. 集合数据结构
9. 数据类型
10. 数据库JDBC
11. 设计模式
12. 开发相关类
13. EJB3
14. 电子邮件
15. 事件
16. 文件输入输出
17. 游戏
18. 泛型
19. GWT
20. Hibernate
21. 本地化
22. J2EE平台
23. 基于J2ME
24. JDK-6
25. JNDI的LDAP
26. JPA
27. JSP技术
28. JSTL
29. 语言基础知识
30. 网络协议
31. PDF格式RTF格式
32. 映射
33. 常规表达式
34. 脚本
35. 安全
36. Servlets
37. Spring
38. Swing组件
39. 图形用户界面
40. SWT-JFace-Eclipse
41. 线程
42. 应用程序
43. Velocity
44. Web服务SOA
45. 可扩展标记语言
Java 教程
Java » 映射 » 屏幕截图 
Make up a compilable version of a given Sun or other API
 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 
 * Java, the Duke mascot, and all variants of Sun's Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun's, and James Gosling's,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/** Make up a compilable version of a given Sun or other API, 
 * so developers can compile against it without a licensed copy. In Sun's case,
 * all public API info is public on Sun's web site, so this does not disclose
 * anything that is Sun Confidential.
 * <p>This is a clean-room implementation: I did not look at the code
 * for Sun's javap or any similar tool in preparing this program.
 * XXX TODO:<ul>
 * <li>Class printing: add superclasses.
 * <li>Collapse common code in printing Constructors and Methods
 * <li>Method printing: add exceptions
 * <li>Arguments: Handle arrays (names begin [L)
 * <li>Provide default (0, false, null) based on type; use in return statements
 *    and in assigment to protected final variables.
 * </ul>
 @author Ian Darwin, http://www.darwinsys.com/
 @version $Id: RevEngAPI.java,v 1.11 2004/05/30 01:43:43 ian Exp $
 */
public class RevEngAPI extends APIFormatter {

  public static void main(String[] argvthrows Exception {
    new RevEngAPI().doArgs(argv);
  }

  private final static String PREFIX_ARG = "arg";
  /** Make up names like "arg0" "arg1", etc. */
  private String mkName(String name, int number) {
    return new StringBuffer(name).append(number).toString();
  }

  /** NOT THREAD SAFE */
  private String className;
  private int classNameOffset;

  /** Generate a .java file for the outline of the given class. */
  public void doClass(Class cthrows IOException {
    className = c.getName();
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.'1;

    // Inner class
    if (className.indexOf('$'!= -1)
      return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.','/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
      out.println("package " + pkg.getName() ';');
      out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i=0; i< ctors.length; i++) {
      if (i == 0) {
        out.println();
        out.println("\t// Constructors");
      }
      Constructor cons = ctors[i];
      int mods = cons.getModifiers();
      if (Modifier.isPrivate(mods))
        continue;
      out.print('\t');
      printMods(mods, out);
      out.print(trim(cons.getName()) "(");
      Class[] classes = cons.getParameterTypes();
      for (int j = 0; j<classes.length; j++) {
        if (j > 0out.print(", ");
        out.print(trim(classes[j].getName()) ' ' 
            mkName(PREFIX_ARG, j));
      }
      out.println(") {");
      out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i=0; i< mems.length; i++) {
      if (i == 0) {
        out.println();
        out.println("\t// Methods");
      }
      Method m = mems[i];
      if (m.getName().startsWith("access$"))
        continue;
      int mods = m.getModifiers();
      if (Modifier.isPrivate(mods))
        continue;
      out.print('\t');
      printMods(mods, out);
      out.print(m.getReturnType());
      out.print(' ');
      out.print(trim(m.getName()) "(");
      Class[] classes = m.getParameterTypes();
      for (int j = 0; j<classes.length; j++) {
        if (j > 0out.print(", ");
        out.print(trim(classes[j].getName()) ' ' 
            mkName(PREFIX_ARG, j));
      }
      out.println(") {");
      out.println("\treturn " + defaultValue(m.getReturnType()) ';');
      out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i=0; i< flds.length; i++) {
      if (i == 0) {
        out.println();
        out.println("\t// Fields");
      }
      Field f = flds[i];
      int mods = f.getModifiers();
      if (Modifier.isPrivate(mods))
        continue;
      out.print('\t');
      printMods(mods, out);
      out.print(trim(f.getType().getName()));
      out.print(' ');
      out.print(f.getName());
      if (Modifier.isFinal(mods)) {
        try {
          out.print(" = " + f.get(null));
        catch (IllegalAccessException ex) {
          out.print("; // " + ex.toString());
        }
      }
      out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
  }

  private String trim(String theName) {
    return theName.startsWith(className?
      theName.substring(classNameOffset: theName;
  }

  private class ModInfo {
    int val;
    String name;
    ModInfo(int v, String n) {
      val = v;
      name = n;
    }
  }

  private ModInfo[] modInfo = {
    new ModInfo(16"final"),
    new ModInfo(2"private"),
    new ModInfo(1"public"),
    new ModInfo(4"protected"),
    new ModInfo(1024"abstract"),
    new ModInfo(8"static"),
    new ModInfo(32"synchronized"),
    new ModInfo(256"native"),
    new ModInfo(128"transient"),
    new ModInfo(64"volatile"),
    new ModInfo(2048"strict"),
  };

  private void printMods(int mods, PrintWriter out) {
    for (int i=0; i < modInfo.length; i++) {
      if ((mods & modInfo[i].val== modInfo[i].val) {
        out.print(modInfo[i].name);
        out.print(' ');
      }
    }
  }

  private String defaultValue(Class c) {
    if (c.getName().equals("boolean"))
      return "false";
    // XXX else if object type return null;
    else return "0";
  }

  public void startFile() {
    // XXX save filename as project name
  }

  public void endFile() {
    // XXX generate a trivial "build.xml" for Ant to create the jar file.
  }
}

/**
 * <p>
 * APIFormatter reads one or more Zip files, gets all entries from each
 * and, for each entry that ends in ".class", loads it with Class.forName()
 * and hands it off to a doClass(Class c) method declared in a subclass.
 * <br/>TODO<br/>
 * Use GETOPT to control doingStandardClasses, verbosity level, etc.
 @author  Ian Darwin, Ian@DarwinSys.com
 @version  $Id: APIFormatter.java,v 1.6 2004/03/14 14:00:34 ian Exp $
 */
abstract class APIFormatter {

  /** True if we are doing classpath, so only do java. and javax. */
  protected static boolean doingStandardClasses = true;
  
  protected int doArgs(String[] argvthrows IOException {
    /** Counter of fields/methods printed. */
    int n = 0;

    // TODO: options
    // -b - process bootclasspath
    // -c - process classpath (default)
    // -s - only process "java." and "javax."

    if (argv.length == 0) {
      // No arguments, look in CLASSPATH
      String s = System.getProperty("java.class.path");
      //  break apart with path sep.
      String pathSep = System.getProperty("path.separator");
      StringTokenizer st = new StringTokenizer(s, pathSep);
      // Process each zip in classpath
      while (st.hasMoreTokens()) {
        String thisFile = st.nextToken();
        System.err.println("Trying path " + thisFile);
        if (thisFile.endsWith(".zip"|| thisFile.endsWith(".jar"))
          processOneZip(thisFile);
      }
    else {
      // We have arguments, process them as zip/jar files
      // doingStandardClasses = false;
      for (int i=0; i<argv.length; i++)
        processOneZip(argv[i]);
    }

    return n;
  }

  /** For each Zip file, for each entry, xref it */
  public void processOneZip(String fileNamethrows IOException {
      List entries = new ArrayList();
      ZipFile zipFile = null;

      try {
        zipFile = new ZipFile(new File(fileName));
      catch (ZipException zz) {
        throw new FileNotFoundException(zz.toString() + fileName);
      }
      Enumeration all = zipFile.entries();

      // Put the entries into the List for sorting...
      while (all.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry)all.nextElement();
        entries.add(zipEntry);
      }

      // Sort the entries (by class name)
      // Collections.sort(entries);

      // Process all the entries in this zip.
      Iterator it = entries.iterator();
      while (it.hasNext()) {
        ZipEntry zipEntry = (ZipEntry)it.next();
        String zipName = zipEntry.getName();

        // Ignore package/directory, other odd-ball stuff.
        if (zipEntry.isDirectory()) {
          continue;
        }

        // Ignore META-INF stuff
        if (zipName.startsWith("META-INF/")) {
          continue;
        }

        // Ignore images, HTML, whatever else we find.
        if (!zipName.endsWith(".class")) {
          continue;
        }

        // If doing CLASSPATH, Ignore com.* which are "internal API".
      //   if (doingStandardClasses && !zipName.startsWith("java")){
      //     continue;
      //   }
      
        // Convert the zip file entry name, like
        //  java/lang/Math.class
        // to a class name like
        //  java.lang.Math
        String className = zipName.replace('/''.').
          substring(0, zipName.length() 6);  // 6 for ".class"

        // Now get the Class object for it.
        Class c = null;
        try {
          c = Class.forName(className);
        catch (ClassNotFoundException ex) {
          System.err.println("Error: " + ex);
        }

        // Hand it off to the subclass...
        doClass(c);
      }
  }

  /** Format the fields and methods of one class, given its name.
   */
  protected abstract void doClass(Class cthrows IOException;
}


           
         
  
Related examples in the same category
1. 类反射:类修饰符类反射:类修饰符
2. 类反射:类名类反射:类名
3. 类反射:特级名称类反射:特级名称
4. 对象反射:创建新的实例
5. 类反射类反射
6. This class shows using Reflection to get a field from another classThis class shows using Reflection to get a field from another class
7. 查看类的关键字和getClass ( )的执行查看类的关键字和getClass ( )的执行
8. Simple Demonstration of a ClassLoader WILL NOT COMPILE OUT OF THE BOX
9. 展现classFor来创建一个对象实例
10. CrossRef prints a cross-reference about all classes named in argv
11. Show a couple of things you can do with a Class object
12. Reflect1 shows the information about the class named in argv
13. Show that you can, in fact, take the class of a primitive
14. JavaP prints structural information about classes
15. 督察对象督察对象
16. Provides a set of static methods that extend the Java metaobject
17. Demonstration of speed of reflexive versus programmatic invocation
18. 使用反射获得控制台字符集
19. 负载类源位置由Class.getResource ( )
20. 从内部类访问内附类
21. Use reflection to dynamically discover the capabilities of a class.
22. 用字符串获取类
23. 用类的方式获取类
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.