Constructor Reflection : Constructor « Reflection « Java






Constructor Reflection

Constructor Reflection
   

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ReflectionTest {
  public static void main(String[] args) {
    String name = "java.util.Date";
    try {
      Class cl = Class.forName(name);
      Class supercl = cl.getSuperclass();
      System.out.print("class " + name);
      if (supercl != null && !supercl.equals(Object.class))
        System.out.println(" extends " + supercl.getName());
      System.out.print("Its constructors:");
      printConstructors(cl);
      System.out.println();
    } catch (ClassNotFoundException e) {
      System.out.println("Class not found.");
    }
  }

  public static void printConstructors(Class cl) {
    Constructor[] constructors = cl.getDeclaredConstructors();

    for (int i = 0; i < constructors.length; i++) {
      Constructor c = constructors[i];
      Class[] paramTypes = c.getParameterTypes();
      String name = c.getName();
      System.out.print(Modifier.toString(c.getModifiers()));
      System.out.print(" " + name + "(");
      for (int j = 0; j < paramTypes.length; j++) {
        if (j > 0)
          System.out.print(", ");
        System.out.print(paramTypes[j].getName());
      }
      System.out.println(");");
    }
  }
}

           
         
    
    
  








Related examples in the same category

1.Creating an Object Using a Constructor Object
2.Class Reflection: find out the constructor informationClass Reflection: find out the constructor information
3.Object Reflection: invoke constructor with parametersObject Reflection: invoke constructor with parameters
4.Get constructors of a class object
5.Create object using Constructor object
6.Getting a Constructor of a Class Object: By obtaining a list of all Constructors object
7.Getting a Constructor of a Class Object: By obtaining a particular Constructor object.
8.Passing a parameter to the constructor and calling a method dynamically
9.Has Declared Constructor
10.Get all construtors from a class
11.Gets an array of all Constructor calls for the given class
12.Adds all Constructor (from Class.getConstructorCalls) to the list
13.Convert the constructor to a Java Code String (arguments are replaced by the simple types)