Various Class Loader utilities : ClassLoader « 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 » ClassLoaderScreenshots 
Various Class Loader utilities
    
/***
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program 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 General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *    Project: www.simpledbm.org
 *    Author : Dibyendu Majumdar
 *    Email  : dibyendu@mazumdar.demon.co.uk
 */

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;


/**
 * Various Class Loader utilities. 
 @author Dibyendu Majumdar
 @since 14.Jan.2005
 */
public final class ClassUtils {

  private static final String LOG_CLASS_NAME = ClassUtils.class.getName();

  /**
   * Get the ClassLoader to use. We always use the current Thread's
   * Context ClassLoader. Assumption is that all threads within the
   * application share the same ClassLoader.
   */
  private static ClassLoader getClassLoader() {
      ClassLoader cl = Thread.currentThread().getContextClassLoader();
      if (cl == null) {
          throw new NullPointerException();
      }
      return cl;
  }
  
  
  /**
   * A wrapper for Class.forName() so that we can change the behaviour
   * globally without changing the rest of the code.
   
   @param name Name of the class to be loaded
   @throws ClassNotFoundException
   */
  public static Class forName(String namethrows ClassNotFoundException {
    ClassLoader cl = getClassLoader();
    Class clazz = null;

    clazz = Class.forName(name, true, cl);
    return clazz;
  }

  /**
   * Load a properties file from the classpath.
   
   @param name Name of the properties file
   @throws IOException If the properties file could not be loaded
   */
  public static InputStream getResourceAsStream(String namethrows IOException {
      ClassLoader cl = getClassLoader();
      InputStream is = null;
        is = cl.getResourceAsStream(name);
      if (is == null) {
          throw new IOException("Unable to load "" " + name);
      }

      return is;
  }
  
  
  /**
   * Load a properties file from the classpath.
   
   @param name Name of the properties file
   @throws IOException If the properties file could not be loaded
   */
  public static Properties getResourceAsProperties(String namethrows IOException {
      ClassLoader cl = getClassLoader();
      InputStream is = null;
        is = cl.getResourceAsStream(name);
      if (is == null) {
          throw new IOException("Unable to load "" " + name);
      }
      Properties props = new Properties();
      props.load(is);

      return props;
  }

  /**
   * Helper for invoking an instance method that takes a single parameter.
   * This method also handles parameters of primitive type.
   
   @param cl
   *            The class that the instance belongs to
   @param instance
   *            The object on which we will invoke the method
   @param methodName
   *            The method name
   @param param
   *            The parameter
   @throws Throwable
   */
  public static Object invokeMethod(Class cl, Object instance,
      String methodName, Object paramthrows Throwable {
      Class paramClass;
      if (param instanceof Integer)
          paramClass = Integer.TYPE;
      else if (param instanceof Long
          paramClass = Long.TYPE;
      else if (param instanceof Short)
          paramClass = Short.TYPE;
      else if (param instanceof Boolean)
          paramClass = Boolean.TYPE;
      else if (param instanceof Double)
          paramClass = Double.TYPE;
      else if (param instanceof Float)
          paramClass = Float.TYPE;
      else if (param instanceof Character)
          paramClass = Character.TYPE;
      else if (param instanceof Byte)
          paramClass = Byte.TYPE;
      else
          paramClass = param.getClass();
    Method method = cl.getMethod(methodName,
        new Class[] { paramClass });
    try {
      return method.invoke(instance, new Object[] { param });
    catch (InvocationTargetException e) {
      throw e.getCause();
    }
  }
  
  /**
   * Helper for invoking a static method that takes one parameter.
   
   @param cl
   *            The class that implements the static method
   @param methodName
   *            The method name
   @param param
   *            A parameter
   @param paramClass
   *            Class of the parameter
   @throws Throwable
   */
  public static Object invokeStaticMethod(Class cl, String methodName,
      Object param, Class paramClassthrows Throwable {
    Method method = cl.getMethod(methodName, new Class[] { paramClass });
    try {
      return method.invoke(null, new Object[] { param });
    catch (InvocationTargetException e) {
      throw e.getCause();
    }
  }

  /**
   * Helper for invoking a constructor with one parameter.
   
   @param className Class of which an instance is to be allocated
   @param param Parameter
   @param paramClass Type of the parameter
   @throws ClassNotFoundException
   @throws SecurityException
   @throws NoSuchMethodException
   @throws IllegalArgumentException
   @throws InstantiationException
   @throws IllegalAccessException
   @throws InvocationTargetException
   */
  public static Object createObject(String className, Object param, Class paramClass)
      throws ClassNotFoundException, SecurityException,
      NoSuchMethodException, IllegalArgumentException,
      InstantiationException, IllegalAccessException,
      InvocationTargetException {
    Class clazzImpl = ClassUtils.forName(className);
    Constructor ctor = clazzImpl
        .getConstructor(new Class[] { paramClass });
    Object instance = ctor.newInstance(new Object[] { param });
    return instance;
  }
}

   
    
    
    
  
Related examples in the same category
1. Determining from Where a Class Was Loaded
2. Loading a Class That Is Not on the Classpath
3. Dynamically Reloading a Modified Class
4. Get the path from where a class is loaded
5. Using the forName() method
6. Unqualified names
7. Return the context classloader.
8. Jar Class Loader
9. Zip Class Loader
10. Load class from Thread's ContextClassLoader, classloader of derived class or the system ClassLoader
11. Load Class
12. Load classes
13. Class Finder
14. Class For Name
15. Context ClassLoader
16. Analyze ClassLoader hierarchy for any given object or class loader
17. A class loader which loads classes using a searchlist of other classloaders
18. Equivalently to invoking Thread.currentThread().getContextClassLoader().loadClass(className); but it supports primitive types and array classes of object types or primitive types.
19. A class to simplify access to resources through the classloader
20. Get a compatible constructor for the given value type
21. Force the given class to be loaded fully.
22. does Class Exist
23. Java interpreter replacement
24. Utility to essentially do Class forName and allow configurable Classloaders.
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.