Java Tutorial/Reflection/Class Loader

Материал из Java эксперт
Версия от 15:19, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Analyze ClassLoader hierarchy for any given object or class loader

/*
 * Copyright 2002-2005 the original author or authors.
 * 
 * Licensed 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.
 */

/**
 * Utility class for diagnostic purposes, to analyze the
 * ClassLoader hierarchy for any given object or class loader.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 02 April 2001
 * @see java.lang.ClassLoader
 */
public abstract class ClassLoaderUtils {
  /**
   * Show the class loader hierarchy for this class.
   * Uses default line break and tab text characters.
   * @param obj object to analyze loader hierarchy for
   * @param role a description of the role of this class in the application
   * (e.g., "servlet" or "EJB reference")
   * @return a String showing the class loader hierarchy for this class
   */
  public static String showClassLoaderHierarchy(Object obj, String role) {
    return showClassLoaderHierarchy(obj, role, "\n", "\t");
  }
  /**
   * Show the class loader hierarchy for this class.
   * @param obj object to analyze loader hierarchy for
   * @param role a description of the role of this class in the application
   * (e.g., "servlet" or "EJB reference")
   * @param lineBreak line break
   * @param tabText text to use to set tabs
   * @return a String showing the class loader hierarchy for this class
   */
  public static String showClassLoaderHierarchy(Object obj, String role, String lineBreak, String tabText) {
    String s = "object of " + obj.getClass() + ": role is " + role + lineBreak;
    return s + showClassLoaderHierarchy(obj.getClass().getClassLoader(), lineBreak, tabText, 0);
  }
  /**
   * Show the class loader hierarchy for the given class loader.
   * Uses default line break and tab text characters.
   * @param cl class loader to analyze hierarchy for
   * @return a String showing the class loader hierarchy for this class
   */
  public static String showClassLoaderHierarchy(ClassLoader cl) {
    return showClassLoaderHierarchy(cl, "\n", "\t");
  }
  /**
   * Show the class loader hierarchy for the given class loader.
   * @param cl class loader to analyze hierarchy for
   * @param lineBreak line break
   * @param tabText text to use to set tabs
   * @return a String showing the class loader hierarchy for this class
   */
  public static String showClassLoaderHierarchy(ClassLoader cl, String lineBreak, String tabText) {
    return showClassLoaderHierarchy(cl, lineBreak, tabText, 0);
  }
  /**
   * Show the class loader hierarchy for the given class loader.
   * @param cl class loader to analyze hierarchy for
   * @param lineBreak line break
   * @param tabText text to use to set tabs
   * @param indent nesting level (from 0) of this loader; used in pretty printing
   * @return a String showing the class loader hierarchy for this class
   */
  private static String showClassLoaderHierarchy(ClassLoader cl, String lineBreak, String tabText, int indent) {
    if (cl == null) {
      ClassLoader ccl = Thread.currentThread().getContextClassLoader();
      return "context class loader=[" + ccl + "] hashCode=" + ccl.hashCode();
    }
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < indent; i++) {
      buf.append(tabText);
    }
    buf.append("[").append(cl).append("] hashCode=").append(cl.hashCode()).append(lineBreak);
    ClassLoader parent = cl.getParent();
    return buf.toString() + showClassLoaderHierarchy(parent, lineBreak, tabText, indent + 1);
  }
}





A tree structure that maps inheritance hierarchies of classes

/*
 * The contents of this file are subject to the Sapient Public License
 * Version 1.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://carbon.sf.net/License.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 *
 * The Original Code is The Carbon Component Framework.
 *
 * The Initial Developer of the Original Code is Sapient Corporation
 *
 * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class creates a tree structure that maps inheritance hierarchies of
 * classes. A developer can place any number of classes into this object and
 * retrieve the closest super class or the class itself.
 *
 *
 * Copyright 2001 Sapient
 * @since EJFW 2.7
 * @author Greg Hinkle, January 2001
 * @version $Revision: 1.4 $($Author: dvoet $ / $Date: 2003/05/05 21:21:23 $)
 */
public class ClassTree {
    protected ClassTreeNode bottom;

    /**
     * Constructs a ClassTree that represents all classes and interfaces that
     * are generalizations of the provided class. This ends up with a tree
     * structure of the inheritance hierarchy for that provided class all the
     * way up to java.lang.Object.
     * @param specificClass The class to build the tree for.
     */
    public ClassTree(Class specificClass) {
        this.bottom = ClassTreeNode.buildNode(specificClass);
    }
    public ClassTreeNode getBottom() {
        return this.bottom;
    }

    /**
     * Constructs an ordered list starting at the highest (most general) class
     * in the tree and moving down the tree, ensuring no generalization comes
     * after one of its specializations.
     * @return a list ordered as above
     */
    public List getOrderedList() {
        List list = new ArrayList();
        list.add(getBottom());
        buildList(getBottom(),list);
        Collections.sort(list);
        // Refactor list into a list of classes from a list of ClassTreeNodes
        for (int i = 0; i < list.size(); i++) {
            ClassTreeNode node = (ClassTreeNode) list.get(i);
            list.set(i,node.getObjectClass());
        }
        // Reverse the list so that the top class in the hierarchy comes first
        Collections.reverse(list);
        return list;
    }
    /**
     * Build breadth first in order to maintain sudo ordering as per
     * class declarations (i.e. if A implements B, C... B is closer in the
     * chain to A than C is, because B comes first in the implements clause.
     *
     * Note that the list coming out here is preordered, but not natural
     * ordered. (i.e. some classes are out of order in relation to classes
     * they have direct relationships with. This is later fixed by a sort
     * on the list by natural ordering. Collecitons.sort, does preserve
     * the preordering for nodes that have no relationship.
     *
     * @param node the node to be browsed.
     * @param output this list is altered to add the contents as they are
     *   browsed in breadth-first order. Start with a list containing only
     *   the bottom node.
     */
    private void buildList(ClassTreeNode node, List output) {
        for (int i = 0; i < node.getParents().size(); i++) {
            ClassTreeNode parent = (ClassTreeNode) node.getParents().get(i);
            if (!output.contains(parent)) {
                output.add(parent);
            }
        }
        List parents = node.getParents();
        for (int i = 0; i < parents.size(); i++) {
            ClassTreeNode parent = (ClassTreeNode) parents.get(i);
            buildList(parent, output);
        }
    }

    /**
     * Inner class representing each node in the tree. Holds references to the
     * nodes children, parent and provides the Comparable interface for sorting
     * by inheritance hierarchy.
     */
    public static class ClassTreeNode implements Comparable {
        /** The class of this node */
        protected Class objectClass;
        /** The map of children classes to their class names */
        protected List children;
        /** A reference to the parent node of this node */
        protected List parents;
        /**
         * Constructs a ClassTreeNode with the given Class.
         *
         * @param objectClass the Class of the node
         */
        public ClassTreeNode(Class objectClass) {
            this.children = new ArrayList();
            this.objectClass = objectClass;
            this.parents = new ArrayList();

        }
        public static ClassTreeNode buildNode(Class objectClass) {
            Map allNodes = new HashMap();
            return buildNode(objectClass, allNodes);
        }
        protected static ClassTreeNode buildNode(Class objectClass, Map allNodes) {
            ClassTreeNode node;
            if (allNodes.containsKey(objectClass)) {
                node = (ClassTreeNode) allNodes.get(objectClass);
            } else {
                node = new ClassTreeNode(objectClass);
                allNodes.put(objectClass, node);
            }
            // Add the implemented interfaces...
            Class[] superInterfaces = objectClass.getInterfaces();
            for (int i = 0; i < superInterfaces.length; i++) {
                Class superInterface = superInterfaces[i];
                ClassTreeNode parent = buildNode(superInterface);
                node.addParent(parent);
            }
            // Add the superclass after the interfaces...
            Class superClass = objectClass.getSuperclass();
            if (superClass != null) {
                ClassTreeNode parent = buildNode(superClass);
                node.addParent(parent);
            }
            return node;
        }

        public List getParents() {
            return this.parents;
        }
        public void addParent(ClassTreeNode node) {
            this.parents.add(node);
            node.addChild(this);
        }
        public boolean removeChild(ClassTreeNode node) {
            return this.children.remove(node);
        }
        public void addChild(ClassTreeNode node) {
            this.children.add(node);
        }
        public List getChildren() {
            return this.children;
        }
        public boolean equals(Object obj) {
            return ((ClassTreeNode)obj).getObjectClass().equals(this.objectClass);
        }
        public Class getObjectClass() {
            return this.objectClass;
        }
        public String getClassName() {
            return this.objectClass.getName();
        }

        public int hashCode() {
            return this.objectClass.hashCode();
        }
        /**
         * Compares one class to another class by their inheritance tree.
         *
         * @return an integer representing the comparison results as follows:<br>
         *    2  if this is a subclass of past in object<br>
         *    -2 if this is a superclass of past in object<br>
         *    0 if they are not related (and in relation to sorting, equal)<br>
         *    0  if they are the same<br>
         */
        public int compareTo(Object obj) {
            Class objClass = ((ClassTreeNode)obj).getObjectClass();
            if (objClass.equals(this.objectClass)) {
                return 0;
            } else if (this.objectClass.isAssignableFrom(objClass)) {
                return 2;
            } else if (objClass.isAssignableFrom(this.objectClass)) {
                return -2;
            } else {
                return 0;
            }
        }
    } // End of ClassTree$ClassTreeNode

}





BufferedReader reflection

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - 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.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
 */
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
public class GrowBufferedReader {
  private static final int srcBufSize = 10 * 1024;
  private static char[] src = new char[srcBufSize];
  static {
    src[srcBufSize - 1] = "x";
  }
  private static CharArrayReader car = new CharArrayReader(src);
  public static void main(String... args) {
    try {
      BufferedReader br = new BufferedReader(car);
      Class<?> c = br.getClass();
      Field f = c.getDeclaredField("cb");
      // cb is a private field
      f.setAccessible(true);
      char[] cbVal = char[].class.cast(f.get(br));
      char[] newVal = Arrays.copyOf(cbVal, cbVal.length * 2);
      if (args.length > 0 && args[0].equals("grow"))
        f.set(br, newVal);
      for (int i = 0; i < srcBufSize; i++)
        br.read();
      // see if the new backing array is being used
      if (newVal[srcBufSize - 1] == src[srcBufSize - 1])
        out.format("Using new backing array, size=%d%n", newVal.length);
      else
        out.format("Using original backing array, size=%d%n", cbVal.length);
      // production code should handle these exceptions more gracefully
    } catch (FileNotFoundException x) {
      x.printStackTrace();
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    } catch (IOException x) {
      x.printStackTrace();
    }
  }
}





Catch InvocationTargetException

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - 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.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
 */
import static java.lang.System.err;
import static java.lang.System.out;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Locale;
public class Deet<T> {
  private boolean testDeet(Locale l) {
    // getISO3Language() may throw a MissingResourceException
    out.format("Locale = %s, ISO Language Code = %s%n", l.getDisplayName(), l
        .getISO3Language());
    return true;
  }
  private int testFoo(Locale l) {
    return 0;
  }
  private boolean testBar() {
    return true;
  }
  public static void main(String... args) {
    if (args.length != 4) {
      err.format("Usage: java Deet <classname> <langauge> <country> <variant>%n");
      return;
    }
    try {
      Class<?> c = Class.forName(args[0]);
      Object t = c.newInstance();
      Method[] allMethods = c.getDeclaredMethods();
      for (Method m : allMethods) {
        String mname = m.getName();
        if (!mname.startsWith("test")|| (m.getGenericReturnType() != boolean.class)) {
          continue;
        }
        Type[] pType = m.getGenericParameterTypes();
        if ((pType.length != 1)|| Locale.class.isAssignableFrom(pType[0].getClass())) {
          continue;
        }
        out.format("invoking %s()%n", mname);
        try {
          m.setAccessible(true);
          Object o = m.invoke(t, new Locale(args[1], args[2], args[3]));
          out.format("%s() returned %b%n", mname, (Boolean) o);
          // Handle any exceptions thrown by method to be invoked.
        } catch (InvocationTargetException x) {
          Throwable cause = x.getCause();
          err.format("invocation of %s failed: %s%n", mname, cause.getMessage());
        }
      }
      // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    } catch (InstantiationException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Context ClassLoader

/**************************************************************************************
 * Copyright (c) Jonas Bon�r, Alexandre Vasseur. All rights reserved.                 *
 * http://aspectwerkz.codehaus.org                                                    *
 * ---------------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the LGPL license      *
 * a copy of which has been included with this distribution in the license.txt file.  *
 **************************************************************************************/

import java.io.InputStream;
import java.net.URL;
/**
 * Utility methods dealing with the context class loader. Fail-over is provided to the default class loader.
 *
 * @author 
 */
public final class ContextClassLoader {
    /**
     * Loads a class starting from the given class loader (can be null, then use default class loader)
     *
     * @param loader
     * @param name   of class to load
     * @return
     * @throws ClassNotFoundException
     */
    public static Class forName(final ClassLoader loader, final String name) throws ClassNotFoundException {
        Class klass = null;
        if (loader != null) {
            klass = Class.forName(name, false, loader);
        } else {
            klass = Class.forName(name, false, ClassLoader.getSystemClassLoader());
        }
        return klass;
    }

    /**
     * Loads a class from the context class loader or, if that fails, from the default class loader.
     *
     * @param name is the name of the class to load.
     * @return a <code>Class</code> object.
     * @throws ClassNotFoundException if the class was not found.
     */
    public static Class forName(final String name) throws ClassNotFoundException {
        Class cls = null;
        try {
            cls = Class.forName(name, false, Thread.currentThread().getContextClassLoader());
        } catch (Exception e) {
            cls = Class.forName(name);
        }
        return cls;
    }
    /**
     * Loads a resource from the context class loader or, if that fails, from the default class loader.
     *
     * @param name is the name of the resource to load.
     * @return a <code>URL</code> object.
     */
    public static URL loadResource(final String name) {
        try {
            return Thread.currentThread().getContextClassLoader().getResource(name);
        } catch (Exception e) {
            return ClassLoader.class.getClassLoader().getResource(name);
        }
    }
//    /**
//     * Loads a resource from the context class loader or, if that fails, from the default class loader, as stream
//     *
//     * @param name is the name of the resource to load.
//     * @return a <code>InputStream</code> object.
//     */
//    public static InputStream getResourceAsStream(final String name) {
//        InputStream stream = null;
//        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
//        if (contextClassLoader != null) {
//            stream = contextClassLoader.getResourceAsStream(name);
//        }
//        if (stream == null) {
//            ClassLoader classLoader = ClassLoader.class.getClassLoader();
//            if (classLoader != null) {
//                stream = classLoader.getResourceAsStream(name);
//            }
//        }
//        return stream;
//    }
    /**
     * Returns the context class loader.
     *
     * @return the context class loader
     */
    public static ClassLoader getLoader() {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = ClassLoader.class.getClassLoader();
        }
        return loader;
    }
}





Create an object from a string

public class Main {
  public static void main(String[] argv) throws Exception {
    Class[] classParm = null;
    Object[] objectParm = null;
    try {
      String name = "java.lang.String";
      Class cl = Class.forName(name);
      java.lang.reflect.Constructor co = cl.getConstructor(classParm);
      System.out.println(co.newInstance(objectParm));
    } catch (Exception e) {
      e.printStackTrace();
      
    }
  }
}





Creating an Object Using a Constructor Object

import java.lang.reflect.Constructor;
public class Main {
  public static void main(String[] argv) throws Exception {
    Constructor con = java.awt.Point.class.getConstructor(new Class[] { int.class, int.class });
    java.awt.Point obj = (java.awt.Point) con.newInstance(new Object[] { new Integer(123),
        new Integer(123) });
  }
}





Determining from Where a Class Was Loaded

import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
public class Main {
  public Main() {
    Class cls = this.getClass();
    ProtectionDomain pDomain = cls.getProtectionDomain();
    CodeSource cSource = pDomain.getCodeSource();
    URL loc = cSource.getLocation();
  }
  public static void main(String[] argv) throws Exception {
  }
}





Dynamically Reloading a Modified Class

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
class MyClass{
  public String myMethod() {
    return "a message";
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    URL[] urls = null;
    File dir = new File(System.getProperty("user.dir") + File.separator + "dir" + File.separator);
    URL url = dir.toURI().toURL();
    urls = new URL[] { url };
    ClassLoader cl = new URLClassLoader(urls);
    Class cls = cl.loadClass("MyClass");
    MyClass myObj = (MyClass) cls.newInstance();
  }
}





extends URLClassLoader

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
class JarClassLoader extends URLClassLoader {
  private URL url;
  public JarClassLoader(URL url) {
    super(new URL[] { url });
    this.url = url;
  }
  public String getMainClassName() throws IOException {
    URL u = new URL("jar", "", url + "!/");
    JarURLConnection uc = (JarURLConnection) u.openConnection();
    Attributes attr = uc.getMainAttributes();
    return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
  }
  public void invokeClass(String name, String[] args) throws ClassNotFoundException,
      NoSuchMethodException, InvocationTargetException {
    Class c = loadClass(name);
    Method m = c.getMethod("main", new Class[] { args.getClass() });
    m.setAccessible(true);
    int mods = m.getModifiers();
    if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
      throw new NoSuchMethodException("main");
    }
    try {
      m.invoke(null, new Object[] { args });
    } catch (IllegalAccessException e) {
    }
  }
}





Get the class By way of an object

public class Main {
  public static void main(String[] argv) throws Exception {
    Object object = new String();
    // By way of an object
    Class cls = object.getClass();
  }
}





Get the class By way of a string

public class Main {
  public static void main(String[] argv) throws Exception {
    Object object = new String();
    try {
      Class cls = Class.forName("java.lang.String");
    } catch (ClassNotFoundException e) {
    }
  }
}





Get the class By way of .class

public class Main {
  public static void main(String[] argv) throws Exception {
    Object object = new String();
    Class cls = java.lang.String.class;
  }
}





how to use reflection to print the names and values of all nonstatic fields of an object

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Random;
public class Main {
  public static void main(String[] args) throws IllegalAccessException {
    Random r = new Random();
    System.out.print(spyFields(r));
    r.nextInt();
    System.out.println("\nAfter calling nextInt:\n");
    System.out.print(spyFields(r));
  }
  public static String spyFields(Object obj) throws IllegalAccessException {
    StringBuffer buffer = new StringBuffer();
    Field[] fields = obj.getClass().getDeclaredFields();
    for (Field f : fields) {
      if (!Modifier.isStatic(f.getModifiers())) {
        f.setAccessible(true);
        Object value = f.get(obj);
        buffer.append(f.getType().getName());
        buffer.append(" ");
        buffer.append(f.getName());
        buffer.append("=");
        buffer.append("" + value);
        buffer.append("\n");
      }
    }
    return buffer.toString();
  }
}





Instantiate unknown class at runtime and call the object"s methods

import java.lang.reflect.Method;
public class Main {
  public static void main(String[] args) throws Exception {
    Class myclass = Class.forName("java.lang.String");
    Method[] methods = myclass.getMethods();
    //Object object = myclass.newInstance();
    for (int i = 0; i < methods.length; i++) {
      System.out.println(methods[i].getName());
      //System.out.println(methods[i].invoke(object));
    }
  }
}
/*
hashCode
compareTo
compareTo
indexOf
indexOf
indexOf
indexOf
equals
toString
charAt
codePointAt
codePointBefore
codePointCount
compareToIgnoreCase
concat
contains
contentEquals
contentEquals
copyValueOf
copyValueOf
endsWith
equalsIgnoreCase
format
format
getBytes
getBytes
getBytes
getBytes
getChars
intern
isEmpty
lastIndexOf
lastIndexOf
lastIndexOf
lastIndexOf
length
matches
offsetByCodePoints
regionMatches
regionMatches
replace
replace
replaceAll
replaceFirst
split
split
startsWith
startsWith
subSequence
substring
substring
toCharArray
toLowerCase
toLowerCase
toUpperCase
toUpperCase
trim
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
getClass
wait
wait
wait
notify
notifyAll
*/





Load Class

// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed 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.beans.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Some reflection utility methods.
 *
 * @author Hardy Ferentschik
 */
public class ReflectionHelper {
  public static Class<?> loadClass(String name, Class<?> caller) throws ClassNotFoundException {
    try {
      //try context classloader, if fails try caller classloader
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if ( loader != null ) {
        return loader.loadClass( name );
      }
    }
    catch ( ClassNotFoundException e ) {
      //trying caller classloader
      if ( caller == null ) {
        throw e;
      }
    }
    return Class.forName( name, true, caller.getClassLoader() );
  }
}





Load classes

/**
 * EasyBeans
 * Copyright (C) 2006 Bull S.A.S.
 * Contact: easybeans@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: ClassUtils.java 3783 2008-07-30 13:44:06Z benoitf $
 * --------------------------------------------------------------------------
 */

/**
 * The <code>ClassUtils</code> class is the central point used to load classes.
 * @author Guillaume Sauthier
 */
public final class ClassUtils {
    /**
     * Default constructor.
     */
    private ClassUtils() {}
    /**
     * Look up the class in the Tread Context ClassLoader and in the "current" ClassLoader.
     * @param className The class name to load
     * @return the corresponding Class instance
     * @throws ClassNotFoundException if the Class was not found.
     */
    public static Class forName(final String className) throws ClassNotFoundException {
        // Load classes from different classloaders :
        // 1. Thread Context ClassLoader
        // 2. ClassUtils ClassLoader
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        Class cls = null;
        try {
            // Try with TCCL
            cls = Class.forName(className, true, tccl);
        } catch (ClassNotFoundException cnfe) {
            // Try now with the classloader used to load ClassUtils
            ClassLoader current = ClassUtils.class.getClassLoader();
            try {
                cls = Class.forName(className, true, current);
            } catch (ClassNotFoundException cnfe2) {
                // If this is still unknown, throw an Exception
                throw cnfe2;
            }
        }
        return cls;
    }
    /**
     * Look up the class in the Tread Context ClassLoader and in the "current" ClassLoader.
     * @param className The class name to load
     * @param clazz a class used to get classloader
     * @return the corresponding Class instance
     * @throws ClassNotFoundException if the Class was not found.
     */
    public static Class forName(final String className, final Class clazz) throws ClassNotFoundException {
        // Load classes from different classloaders :
        // 1. Thread Context ClassLoader
        // 2. ClassUtils ClassLoader
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        Class cls = null;
        try {
            // Try with TCCL
            cls = Class.forName(className, true, tccl);
        } catch (ClassNotFoundException cnfe) {
            // Try now with the classloader used to load ClassUtils
            ClassLoader current = clazz.getClassLoader();
            if (current != null) {
                try {
                    cls = Class.forName(className, true, current);
                } catch (ClassNotFoundException cnfe2) {
                    // If this is still unknown, throw an Exception
                    throw new ClassNotFoundException("Class Not found in current ThreadClassLoader "" + tccl + "" and in "" + current + "" classloaders.", cnfe2);
                }
            } else {
                // rethrow exception
                throw cnfe;
            }
        }
        return cls;
    }

}





Runs a jar application from any url

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
class JarClassLoader extends URLClassLoader {
  private URL url;
  public JarClassLoader(URL url) {
    super(new URL[] { url });
    this.url = url;
  }
  public String getMainClassName() throws IOException {
    URL u = new URL("jar", "", url + "!/");
    JarURLConnection uc = (JarURLConnection) u.openConnection();
    Attributes attr = uc.getMainAttributes();
    return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
  }
  public void invokeClass(String name, String[] args) throws ClassNotFoundException,
      NoSuchMethodException, InvocationTargetException {
    Class c = loadClass(name);
    Method m = c.getMethod("main", new Class[] { args.getClass() });
    m.setAccessible(true);
    int mods = m.getModifiers();
    if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
      throw new NoSuchMethodException("main");
    }
    try {
      m.invoke(null, new Object[] { args });
    } catch (IllegalAccessException e) {
    }
  }
}
public class JarRunner {
    public static void main(String[] args) throws Exception {
        URL url = new URL(args[0]);
        JarClassLoader cl = new JarClassLoader(url);
        String name = null;
            name = cl.getMainClassName();
        if (name == null) {
            fatal("Specified jar file does not contain a "Main-Class"" +
                  " manifest attribute");
        }
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, newArgs.length);
            cl.invokeClass(name, newArgs);
    }
    private static void fatal(String s) {
        System.err.println(s);
    }
}





URL class loader

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class MainClass {
  static public void main(String args[]) throws Exception {
    URL myurl[] = { new URL("file:///C:/CH3/ClassLoader/web/"),
        new URL("http://www.jexp.edu/~xyx/test/") };
    URLClassLoader x = new URLClassLoader(myurl);
    Class c = x.loadClass("TestURL");
    Class getArg1[] = { (new String[1]).getClass() };
    Method m = c.getMethod("main", getArg1);
    String[] my1 = { "arg1 passed", "arg2 passed" };
    Object myarg1[] = { my1 };
    m.invoke(null, myarg1);
    Object ob = c.newInstance();
    Class arg2[] = {};
    Method m2 = c.getMethod("tt", arg2);
    m2.invoke(ob, null);
    Class arg3[] = { (new String()).getClass(), int.class };
    Method m3 = c.getMethod("tt", arg3);
    Object myarg2[] = { "Arg1", new Integer(100) };
    m3.invoke(ob, myarg2);
  }
}





Using the forName() method

public class Main {
  public static void main(String[] argv) throws Exception {
    Class cc = null;
    cc = Class.forName("Main.class");
  }
}