Java Tutorial/Reflection/Constructor

Материал из Java эксперт
Перейти к: навигация, поиск

A program that displays a class synopsis for the named class

/*
 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.ru/javaexamples3.
 */
//package je3.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/** A program that displays a class synopsis for the named class */
public class ShowClass {
  /** The main method. Print info about the named class */
  public static void main(String[] args) throws ClassNotFoundException {
    Class c = Class.forName(args[0]);
    print_class(c);
  }
  /**
   * Display the modifiers, name, superclass and interfaces of a class or
   * interface. Then go and list all constructors, fields, and methods.
   */
  public static void print_class(Class c) {
    // Print modifiers, type (class or interface), name and superclass.
    if (c.isInterface()) {
      // The modifiers will include the "interface" keyword here...
      System.out.print(Modifier.toString(c.getModifiers()) + " " + typename(c));
    } else if (c.getSuperclass() != null) {
      System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c) + " extends "
          + typename(c.getSuperclass()));
    } else {
      System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c));
    }
    // Print interfaces or super-interfaces of the class or interface.
    Class[] interfaces = c.getInterfaces();
    if ((interfaces != null) && (interfaces.length > 0)) {
      if (c.isInterface())
        System.out.print(" extends ");
      else
        System.out.print(" implements ");
      for (int i = 0; i < interfaces.length; i++) {
        if (i > 0)
          System.out.print(", ");
        System.out.print(typename(interfaces[i]));
      }
    }
    System.out.println(" {"); // Begin class member listing.
    // Now look up and display the members of the class.
    System.out.println("  // Constructors");
    Constructor[] constructors = c.getDeclaredConstructors();
    for (int i = 0; i < constructors.length; i++)
      // Display constructors.
      print_method_or_constructor(constructors[i]);
    System.out.println("  // Fields");
    Field[] fields = c.getDeclaredFields(); // Look up fields.
    for (int i = 0; i < fields.length; i++)
      // Display them.
      print_field(fields[i]);
    System.out.println("  // Methods");
    Method[] methods = c.getDeclaredMethods(); // Look up methods.
    for (int i = 0; i < methods.length; i++)
      // Display them.
      print_method_or_constructor(methods[i]);
    System.out.println("}"); // End class member listing.
  }
  /** Return the name of an interface or primitive type, handling arrays. */
  public static String typename(Class t) {
    String brackets = "";
    while (t.isArray()) {
      brackets += "[]";
      t = t.getComponentType();
    }
    String name = t.getName();
    int pos = name.lastIndexOf(".");
    if (pos != -1)
      name = name.substring(pos + 1);
    return name + brackets;
  }
  /** Return a string version of modifiers, handling spaces nicely. */
  public static String modifiers(int m) {
    if (m == 0)
      return "";
    else
      return Modifier.toString(m) + " ";
  }
  /** Print the modifiers, type, and name of a field */
  public static void print_field(Field f) {
    System.out.println("  " + modifiers(f.getModifiers()) + typename(f.getType()) + " "
        + f.getName() + ";");
  }
  /**
   * Print the modifiers, return type, name, parameter types and exception type
   * of a method or constructor. Note the use of the Member interface to allow
   * this method to work with both Method and Constructor objects
   */
  public static void print_method_or_constructor(Member member) {
    Class returntype = null, parameters[], exceptions[];
    if (member instanceof Method) {
      Method m = (Method) member;
      returntype = m.getReturnType();
      parameters = m.getParameterTypes();
      exceptions = m.getExceptionTypes();
      System.out.print("  " + modifiers(member.getModifiers()) + typename(returntype) + " "
          + member.getName() + "(");
    } else {
      Constructor c = (Constructor) member;
      parameters = c.getParameterTypes();
      exceptions = c.getExceptionTypes();
      System.out.print("  " + modifiers(member.getModifiers()) + typename(c.getDeclaringClass())
          + "(");
    }
    for (int i = 0; i < parameters.length; i++) {
      if (i > 0)
        System.out.print(", ");
      System.out.print(typename(parameters[i]));
    }
    System.out.print(")");
    if (exceptions.length > 0)
      System.out.print(" throws ");
    for (int i = 0; i < exceptions.length; i++) {
      if (i > 0)
        System.out.print(", ");
      System.out.print(typename(exceptions[i]));
    }
    System.out.println(";");
  }
}





Call Private constructor

/*
 * 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 java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Deny {
  private Deny() {
    System.out.format("Deny constructor%n");
  }
}
public class ConstructorTroubleAccess {
  public static void main(String... args) {
    try {
      Constructor c = Deny.class.getDeclaredConstructor();
      // c.setAccessible(true); // solution
      c.newInstance();
      // production code should handle these exceptions more gracefully
    } catch (InvocationTargetException x) {
      x.printStackTrace();
    } catch (NoSuchMethodException x) {
      x.printStackTrace();
    } catch (InstantiationException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Create new instance from Constructor

/*
 * 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.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
class EmailAliases {
  private Set<String> aliases;
  private EmailAliases(HashMap<String, String> h) {
    aliases = h.keySet();
  }
  public void printKeys() {
    out.format("Mail keys:%n");
    for (String k : aliases)
      out.format("  %s%n", k);
  }
}
public class RestoreAliases {
  private static Map<String, String> defaultAliases = new HashMap<String, String>();
  static {
    defaultAliases.put("Duke", "duke@i-love-java");
    defaultAliases.put("Fang", "fang@evil-jealous-twin");
  }
  public static void main(String... args) {
    try {
      Constructor ctor = EmailAliases.class.getDeclaredConstructor(HashMap.class);
      ctor.setAccessible(true);
      EmailAliases email = (EmailAliases) ctor.newInstance(defaultAliases);
      email.printKeys();
      // production code should handle these exceptions more gracefully
    } catch (InstantiationException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    } catch (InvocationTargetException x) {
      x.printStackTrace();
    } catch (NoSuchMethodException x) {
      x.printStackTrace();
    }
  }
}





Demonstrates use of Constructor objects

/*
 *     file: ConstructorDemo.java
 *  package: oreilly.hcj.reflection
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */

import java.lang.reflect.Constructor;
/**  
 * Demonstrates use of Constructor objects.
 *
 * @author 
 * @version $Revision$
 */
public class ConstructorDemo {
  /** 
   * Run the demo.
   *
   * @param args Command line arguments.
   */
  public static void main(final String[] args) {
    try {
      final Class[] ARG_TYPES = new Class[] { String.class };
      Constructor cst = Integer.class.getConstructor(ARG_TYPES);
      System.out.println(cst.newInstance(new Object[] { "45" }));
    } catch (final Exception ex) {
      ex.printStackTrace();
    }
  }
}
/* ########## End of File ########## */





Get a compatible constructor for the given value type

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
public class Main {
  /////////////////////////////////////////////////////////////////////////
  //                           Coercion Methods                          //
  /////////////////////////////////////////////////////////////////////////
  /**
   * Get a compatible constructor for the given value type
   *
   * @param type       Class to look for constructor in
   * @param valueType  Argument type for constructor
   * @return           Constructor or null
   */
  public static Constructor getCompatibleConstructor(final Class type,
                                                     final Class valueType)
  {
     // first try and find a constructor with the exact argument type
     try {
        return type.getConstructor(new Class[] { valueType });
     }
     catch (Exception ignore) {
        // if the above failed, then try and find a constructor with
        // an compatible argument type
        // get an array of compatible types
        Class[] types = type.getClasses();
        for (int i=0; i<types.length; i++) {
           try {
              return type.getConstructor(new Class[] { types[i] });
           }
           catch (Exception ignore2) {}
        }
     }
     // if we get this far, then we can"t find a compatible constructor
     return null;
  }
}





Get all constructors or by parameters

import java.lang.reflect.Constructor;
public class GetConstructor {
    public static void main(String[] args) {
        Constructor[] cs = String.class.getConstructors();
        for(int i=0;i<cs.length;i++){
            System.out.println(cs[i]);        
        }
        try {
            Constructor c = String.class.getConstructor(new Class[]{String.class});
            System.out.println(c); 
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}





Get constructor by parameter type

/*
 * 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.lang.reflect.InvocationTargetException;
public class ConstructorTroubleAgain {
  public ConstructorTroubleAgain() {
  }
  public ConstructorTroubleAgain(Integer i) {
  }
  public ConstructorTroubleAgain(Object o) {
    out.format("Constructor passed Object%n");
  }
  public ConstructorTroubleAgain(String s) {
    out.format("Constructor passed String%n");
  }
  public static void main(String... args) {
    String argType = (args.length == 0 ? "" : args[0]);
    try {
      Class<?> c = Class.forName("ConstructorTroubleAgain");
      if ("".equals(argType)) {
        // IllegalArgumentException: wrong number of arguments
        Object o = c.getConstructor().newInstance("foo");
      } else if ("int".equals(argType)) {
        // NoSuchMethodException - looking for int, have Integer
        Object o = c.getConstructor(int.class);
      } else if ("Object".equals(argType)) {
        // newInstance() does not perform method resolution
        Object o = c.getConstructor(Object.class).newInstance("foo");
      } else {
        assert false;
      }
      // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    } catch (NoSuchMethodException x) {
      x.printStackTrace();
    } catch (InvocationTargetException x) {
      x.printStackTrace();
    } catch (InstantiationException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Getting a Constructor of a Class Object: By obtaining a list of all Constructors object

import java.lang.reflect.Constructor;
public class Main {
  public static void main(String[] argv) throws Exception {
    Constructor[] cons = String.class.getDeclaredConstructors();
    for (int i = 0; i < cons.length; i++) {
      Class[] paramTypes = cons[i].getParameterTypes();
      System.out.println(cons[i]);
    }
  }
}





Getting a Constructor of a Class Object: By obtaining a particular 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 });
    System.out.println(con);
  }
}





Has Declared Constructor

import java.lang.reflect.Constructor;
public class ReflectionUtils {
  public static boolean hasDeclaredConstructor(Class targetClass, Class[] partypes) {
    Constructor constructor = null;
    try {
      constructor = targetClass.getConstructor(partypes);
    }catch (Exception e) {
      e.printStackTrace();
    }
    return constructor != null;
  }
  
}





Invoke a constructor which throws Exception

/*
 * 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 java.lang.reflect.InvocationTargetException;
public class ConstructorTroubleToo {
  public ConstructorTroubleToo() {
    throw new RuntimeException("exception in constructor");
  }
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName("ConstructorTroubleToo");
      // Method propagetes any exception thrown by the constructor (including checked exceptions).
      if (args.length > 0 && args[0].equals("class")) {
        Object o = c.newInstance();
      } else {
        Object o = c.getConstructor().newInstance();
      }
      // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    } catch (InstantiationException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    } catch (NoSuchMethodException x) {
      x.printStackTrace();
    } catch (InvocationTargetException x) {
      x.printStackTrace();
      err.format("%n%nCaught exception: %s%n", x.getCause());
    }
  }
}





Load class with Class.forName

/*
 * 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.
 */
public class ConstructorTrouble {
  private ConstructorTrouble(int i) {
  }
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName("ConstructorTrouble");
      Object o = c.newInstance(); // InstantiationException
      // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    } catch (InstantiationException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}





Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED

/*
 * 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.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
public class ConstructorAccess {
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      Constructor[] allConstructors = c.getDeclaredConstructors();
      for (Constructor ctor : allConstructors) {
        int searchMod = modifierFromString(args[1]);
        int mods = accessModifiers(ctor.getModifiers());
        if (searchMod == mods) {
          out.format("%s%n", ctor.toGenericString());
          out.format("  [ synthetic=%-5b var_args=%-5b ]%n",
              ctor.isSynthetic(), ctor.isVarArgs());
        }
      }
      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  private static int accessModifiers(int m) {
    return m & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED);
  }
  private static int modifierFromString(String s) {
    if ("public".equals(s))
      return Modifier.PUBLIC;
    else if ("protected".equals(s))
      return Modifier.PROTECTED;
    else if ("private".equals(s))
      return Modifier.PRIVATE;
    else if ("package-private".equals(s))
      return 0;
    else
      return -1;
  }
}





Passing a parameter to the constructor and calling a method dynamically

public class Main {
  public static void main(String args[]) throws Exception{
      String name = "java.lang.String";
      String methodName = "toLowerCase";
      Class cl = Class.forName(name);
      java.lang.reflect.Constructor constructor = cl.getConstructor(new Class[] { String.class });
      Object invoker = constructor.newInstance(new Object[] { "AAA" });
      Class arguments[] = new Class[] {};
      java.lang.reflect.Method objMethod = cl.getMethod(methodName, arguments);
      Object result = objMethod.invoke(invoker, (Object[]) arguments);
      System.out.println(result);
  }
}