Manipulate Java classes : Class « Reflection « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Reflection » ClassScreenshots 
Manipulate Java classes
  
/*

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * This class contains utility methods to manipulate Java classes.
 *
 @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
 @version $Id: ClassFileUtilities.java 599691 2007-11-30 03:37:58Z cam $
 */
public class ClassFileUtilities {

    // Constant pool info tags
    public static final byte CONSTANT_UTF8_INFO                = 1;
    public static final byte CONSTANT_INTEGER_INFO             = 3;
    public static final byte CONSTANT_FLOAT_INFO               = 4;
    public static final byte CONSTANT_LONG_INFO                = 5;
    public static final byte CONSTANT_DOUBLE_INFO              = 6;
    public static final byte CONSTANT_CLASS_INFO               = 7;
    public static final byte CONSTANT_STRING_INFO              = 8;
    public static final byte CONSTANT_FIELDREF_INFO            = 9;
    public static final byte CONSTANT_METHODREF_INFO           = 10;
    public static final byte CONSTANT_INTERFACEMETHODREF_INFO  = 11;
    public static final byte CONSTANT_NAMEANDTYPE_INFO         = 12;

    /**
     * This class does not need to be instantiated.
     */
    protected ClassFileUtilities() {
    }

    /**
     * Program that computes the dependencies between the Batik jars.
     * <p>
     *   Run this from the main Batik distribution directory, after building
     *   the jars.  For every jar file in the batik-xxx/ build directory,
     *   it will determine which other jar files it directly depends on.
     *   The output is lines of the form:
     * </p>
     * <pre>  <i>number</i>,<i>from</i>,<i>to</i></pre>
     * <p>
     *   where mean that the <i>from</i> jar has <i>number</i> class files
     *   that depend on class files in the <i>to</i> jar.
     * </p>
     */
    public static void main(String[] args) {
        boolean showFiles = false;
        if (args.length == && args[0].equals("-f")) {
            showFiles = true;
        else if (args.length != 0) {
            System.err.println("usage: ClassFileUtilities [-f]");
            System.err.println();
            System.err.println("  -f    list files that cause each jar file dependency");
            System.exit(1);
        }

        File cwd = new File(".");
        File buildDir = null;
        String[] cwdFiles = cwd.list();
        for (int i = 0; i < cwdFiles.length; i++) {
            if (cwdFiles[i].startsWith("batik-")) {
                buildDir = new File(cwdFiles[i]);
                if (!buildDir.isDirectory()) {
                    buildDir = null;
                else {
                    break;
                }
            }
        }
        if (buildDir == null || !buildDir.isDirectory()) {
            System.out.println("Directory 'batik-xxx' not found in current directory!");
            return;
        }

        try {
            Map cs = new HashMap();
            Map js = new HashMap();
            collectJars(buildDir, js, cs);

            Set classpath = new HashSet();
            Iterator i = js.values().iterator();
            while (i.hasNext()) {
                classpath.add(((Jari.next()).jarFile);
            }

            i = cs.values().iterator();
            while (i.hasNext()) {
                ClassFile fromFile = (ClassFilei.next();
                // System.out.println(fromFile.name);
                Set result = getClassDependencies(fromFile.getInputStream(),
                                                  classpath, false);
                Iterator j = result.iterator();
                while (j.hasNext()) {
                    ClassFile toFile = (ClassFilecs.get(j.next());
                    if (fromFile != toFile && toFile != null) {
                        fromFile.deps.add(toFile);
                    }
                }
            }

            i = cs.values().iterator();
            while (i.hasNext()) {
                ClassFile fromFile = (ClassFilei.next();
                Iterator j = fromFile.deps.iterator();
                while (j.hasNext()) {
                    ClassFile toFile = (ClassFilej.next();
                    Jar fromJar = fromFile.jar;
                    Jar toJar = toFile.jar;
                    if (fromFile.name.equals(toFile.name)
                            || toJar == fromJar
                            || fromJar.files.contains(toFile.name)) {
                        continue;
                    }
                    Integer n = (IntegerfromJar.deps.get(toJar);
                    if (n == null) {
                        fromJar.deps.put(toJar, new Integer(1));
                    else {
                        fromJar.deps.put(toJar, new Integer(n.intValue() 1));
                    }
                }
            }

            List triples = new ArrayList(10);
            i = js.values().iterator();
            while (i.hasNext()) {
                Jar fromJar = (Jari.next();
                Iterator j = fromJar.deps.keySet().iterator();
                while (j.hasNext()) {
                    Jar toJar = (Jarj.next();
                    Triple t = new Triple();
                    t.from = fromJar;
                    t.to = toJar;
                    t.count = ((IntegerfromJar.deps.get(toJar)).intValue();
                    triples.add(t);
                }
            }
            Collections.sort(triples);

            i = triples.iterator();
            while (i.hasNext()) {
                Triple t = (Triplei.next();
                System.out.println
                    (t.count + "," + t.from.name + "," + t.to.name);
                if (showFiles) {
                    Iterator j = t.from.files.iterator();
                    while (j.hasNext()) {
                        ClassFile fromFile = (ClassFilej.next();
                        Iterator k = fromFile.deps.iterator();
                        while (k.hasNext()) {
                            ClassFile toFile = (ClassFilek.next();
                            if (toFile.jar == t.to
                                    && !t.from.files.contains(toFile.name)) {
                                System.out.println
                                    ("\t" + fromFile.name + " --> "
                                          + toFile.name);
                            }
                        }
                    }
                }
            }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected static class ClassFile {
        public String name;
        public List deps = new ArrayList(10);
        public Jar jar;
        public InputStream getInputStream() throws IOException {
            return jar.jarFile.getInputStream(jar.jarFile.getEntry(name));
        }
    }

    protected static class Jar {
        public String name;
        public File file;
        public JarFile jarFile;
        public Map deps = new HashMap();
        public Set files = new HashSet();
    }

    protected static class Triple implements Comparable {
        public Jar from;
        public Jar to;
        public int count;
        public int compareTo(Object o) {
            return ((Tripleo).count - count;
        }
    }

    private static void collectJars(File dir, Map jars, Map classFilesthrows IOException {
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            String n = files[i].getName();
            if (n.endsWith(".jar"&& files[i].isFile()) {
                Jar j = new Jar();
                j.name = files[i].getPath();
                j.file = files[i];
                j.jarFile = new JarFile(files[i]);
                jars.put(j.name, j);

                Enumeration entries = j.jarFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry ze = (ZipEntryentries.nextElement();
                    String name = ze.getName();
                    if (name.endsWith(".class")) {
                        ClassFile cf = new ClassFile();
                        cf.name = name;
                        cf.jar = j;
                        classFiles.put(j.name + '!' + cf.name, cf);
                        j.files.add(cf);
                    }
                }
            else if (files[i].isDirectory()) {
                collectJars(files[i], jars, classFiles);
            }
        }
    }

    /**
     * Returns the dependencies of the given class.
     @param path The root class path.
     @param classpath The set of directories (Strings) to scan.
     @param rec Whether to follow dependencies recursively.
     @return a list of paths representing the used classes.
     */
    public static Set getClassDependencies(String path,
                                           Set classpath,
                                           boolean rec)
            throws IOException {

        return getClassDependencies(new FileInputStream(path), classpath, rec);
    }

    public static Set getClassDependencies(InputStream is,
                                           Set classpath,
                                           boolean rec)
            throws IOException {

        Set result = new HashSet();
        Set done = new HashSet();

        computeClassDependencies(is, classpath, done, result, rec);

        return result;
    }

    private static void computeClassDependencies(InputStream is,
                                                 Set classpath,
                                                 Set done,
                                                 Set result,
                                                 boolean rec)
            throws IOException {

        Iterator it = getClassDependencies(is).iterator();
        while (it.hasNext()) {
            String s = (String)it.next();
            if (!done.contains(s)) {
                done.add(s);

                Iterator cpit = classpath.iterator();
                while (cpit.hasNext()) {
                    InputStream depis = null;
                    String path = null;
                    Object cpEntry = cpit.next();
                    if (cpEntry instanceof JarFile) {
                        JarFile jarFile = (JarFilecpEntry;
                        String classFileName = s + ".class";
                        ZipEntry ze = jarFile.getEntry(classFileName);
                        if (ze != null) {
                            path = jarFile.getName() '!' + classFileName;
                            depis = jarFile.getInputStream(ze);
                        }
                    else {
                        path = ((StringcpEntry'/' + s + ".class";
                        File f = new File(path);
                        if (f.isFile()) {
                            depis = new FileInputStream(f);
                        }
                    }

                    if (depis != null) {
                        result.add(path);

                        if (rec) {
                            computeClassDependencies
                                (depis, classpath, done, result, rec);
                        }
                    }
                }
            }
        }
    }

    /**
     * Returns the dependencies of the given class.
     @return a list of strings representing the used classes.
     */
    public static Set getClassDependencies(InputStream isthrows IOException {
        DataInputStream dis = new DataInputStream(is);

        if (dis.readInt() != 0xcafebabe) {
            throw new IOException("Invalid classfile");
        }

        dis.readInt();

        int len = dis.readShort();
        String[] strs = new String[len];
        Set classes = new HashSet();
        Set desc = new HashSet();

        for (int i = 1; i < len; i++) {
            int constCode = dis.readByte() 0xff;
            switch constCode ) {
            case CONSTANT_LONG_INFO:
            case CONSTANT_DOUBLE_INFO:
                dis.readLong();
                i++;
                break;

            case CONSTANT_FIELDREF_INFO:
            case CONSTANT_METHODREF_INFO:
            case CONSTANT_INTERFACEMETHODREF_INFO:
            case CONSTANT_INTEGER_INFO:
            case CONSTANT_FLOAT_INFO:
                dis.readInt();
                break;

            case CONSTANT_CLASS_INFO:
                classes.add(new Integer(dis.readShort() 0xffff));
                break;

            case CONSTANT_STRING_INFO:
                dis.readShort();
                break;

            case CONSTANT_NAMEANDTYPE_INFO:
                dis.readShort();
                desc.add(new Integer(dis.readShort() 0xffff));
                break;

            case CONSTANT_UTF8_INFO:
                strs[i= dis.readUTF();
                break;

            default:
                throw new RuntimeException("unexpected data in constant-pool:" + constCode );
            }
        }

        Set result = new HashSet();

        Iterator it = classes.iterator();
        while (it.hasNext()) {
            result.add(strs[((Integer)it.next()).intValue()]);
        }

        it = desc.iterator();
        while (it.hasNext()) {
            result.addAll(getDescriptorClasses(strs[((Integer)it.next()).intValue()]));
        }

        return result;
    }

    /**
     * Returns the classes contained in a field or method desciptor.
     */
    protected static Set getDescriptorClasses(String desc) {
        Set result = new HashSet();
        int  i = 0;
        char c = desc.charAt(i);
        switch (c) {
        case '(':
            loop: for (;;) {
                c = desc.charAt(++i);
                switch (c) {
                case '[':
                    do {
                        c = desc.charAt(++i);
                    while (c == '[');
                    if (c != 'L') {
                        break;
                    }

                case 'L':
                    c = desc.charAt(++i);
                    StringBuffer sb = new StringBuffer();
                    while (c != ';') {
                        sb.append(c);
                        c = desc.charAt(++i);
                    }
                    result.add(sb.toString());
                    break;

                default:
                    break;

                case ')':
                    break loop;
                }
            }
            c = desc.charAt(++i);
            switch (c) {
            case '[':
                do {
                    c = desc.charAt(++i);
                while (c == '[');
                if (c != 'L') {
                    break;
                }

            case 'L':
                c = desc.charAt(++i);
                StringBuffer sb = new StringBuffer();
                while (c != ';') {
                    sb.append(c);
                    c = desc.charAt(++i);
                }
                result.add(sb.toString());
                break;

            default:
            case 'V':
            }
            break;

        case '[':
            do {
                c = desc.charAt(++i);
            while (c == '[');
            if (c != 'L') {
                break;
            }

        case 'L':
            c = desc.charAt(++i);
            StringBuffer sb = new StringBuffer();
            while (c != ';') {
                sb.append(c);
                c = desc.charAt(++i);
            }
            result.add(sb.toString());
            break;

        default:
        }

        return result;
    }
}

   
    
  
Related examples in the same category
1. Class Reflection: class modifierClass Reflection: class modifier
2. Class Reflection: class nameClass Reflection: class name
3. Class Reflection: name for super classClass Reflection: name for super class
4. Object Reflection: create new instance
5. Class reflectionClass reflection
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. Show the class keyword and getClass() method in actionShow the class keyword and getClass() method in action
8. Simple Demonstration of a ClassLoader WILL NOT COMPILE OUT OF THE BOX
9. Demonstrate classFor to create an instance of an object
10. CrossRef prints a cross-reference about all classes named in argv
11. Make up a compilable version of a given Sun or other API
12. Show a couple of things you can do with a Class object
13. Reflect1 shows the information about the class named in argv
14. Show that you can, in fact, take the class of a primitive
15. JavaP prints structural information about classes
16. Object InspectorObject Inspector
17. Provides a set of static methods that extend the Java metaobject
18. Demonstration of speed of reflexive versus programmatic invocation
19. Use reflection to get console char set
20. Load the class source location from Class.getResource()
21. Access the enclosing class from an inner class
22. Use reflection to dynamically discover the capabilities of a class.
23. Get the class By way of a string
24. Get the class By way of .class
25. Return a String representation of an object's overall identity
26. Manipulate Java class files in strange and mysterious ways
27. Class file reader for obtaining the parameter names for declared methods in a class
28. Convert a given String into the appropriate Class.
29. Encapsulates a class serialVersionUID and codebase.
30. Dump a class using Reflection
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.