Java Class.getDeclaredConstructors Examples

Java Class.getDeclaredConstructors - 30 examples found. These are the top rated real world Java examples of Class.getDeclaredConstructors extracted from open source projects. You can rate examples to help us improve the quality of examples.
  /**
   * Create a default object of the given type. Prefers constructors with as few arguments as
   * possible. Creates an empty proxy for interfaces.
   *
   * @param type type to instantiate
   * @return default instance
   * @throws Exception if the default instance could not be created
   */
  private static Object instantiateType(Class<?> type) throws Exception {
    if (type.isPrimitive()) return Defaults.defaultValue(type);
    else if (type == Void.class) return null;
    else if (type.isArray()) return Array.newInstance(type, 0);
    else if (type.isInterface())
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          new Class[] {type},
          new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
              return null;
            }
          });

    // Take a constructor with as few params as possible
    Constructor constructor = type.getDeclaredConstructors()[0];
    for (Constructor<?> c : type.getDeclaredConstructors()) {
      if (c.getParameterTypes().length < constructor.getParameterTypes().length) constructor = c;
    }

    Object[] params = new Object[constructor.getParameterTypes().length];
    for (int i = 0; i < constructor.getParameterTypes().length; i++) {
      params[i] = instantiateType(constructor.getParameterTypes()[i]);
    }
    return constructor.newInstance(params);
  }
Example #2
0
 private static <T> void checkIsValidPartial(Class<T> cls) {
   checkArgument(isAbstract(cls.getModifiers()), "Partial class must be abstract");
   checkArgument(
       cls.getDeclaredConstructors().length == 1,
       "Partial class %s must have exactly one constructor (found %s)",
       cls,
       cls.getDeclaredConstructors().length);
   Constructor<?> constructor = cls.getDeclaredConstructors()[0];
   checkArgument(
       !isPrivate(constructor.getModifiers()),
       "Partial class %s must have a package-visible constructor",
       cls);
 }
  private void validateClass(Class<?> source, ValidationProblemCollector problems) {
    int modifiers = source.getModifiers();

    if (Modifier.isInterface(modifiers)) {
      problems.add("Must be a class, not an interface");
    }

    if (source.getEnclosingClass() != null) {
      if (Modifier.isStatic(modifiers)) {
        if (Modifier.isPrivate(modifiers)) {
          problems.add("Class cannot be private");
        }
      } else {
        problems.add("Enclosed classes must be static and non private");
      }
    }

    Constructor<?>[] constructors = source.getDeclaredConstructors();
    for (Constructor<?> constructor : constructors) {
      if (constructor.getParameterTypes().length > 0) {
        problems.add("Cannot declare a constructor that takes arguments");
        break;
      }
    }

    Field[] fields = source.getDeclaredFields();
    for (Field field : fields) {
      int fieldModifiers = field.getModifiers();
      if (!field.isSynthetic()
          && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) {
        problems.add(field, "Fields must be static final.");
      }
    }
  }
  /**
   * This class returns a ClassStatsHolder object which holds statistics about a class
   *
   * @param classname
   * @return
   */
  private ClassStatsHolder getStatistics(String classname) {
    ClassStatsHolder ret = null;
    try {
      // get methods, constructors etc
      Class theClass = Class.forName(classname);
      Integer numFields = theClass.getDeclaredFields().length;
      Method[] methods = theClass.getDeclaredMethods();
      Integer members = (theClass.getDeclaredFields().length) + methods.length;
      Constructor[] constructors = theClass.getDeclaredConstructors();

      // create ararys of method names an number of parameters
      String[] totalMethods = new String[methods.length];
      Integer[] paramaters = new Integer[methods.length];
      for (int i = 0; i < methods.length; i++) {
        totalMethods[i] = methods[i].getName();
        paramaters[i] = methods[i].getParameterTypes().length;
      }

      ret =
          new ClassStatsHolder(
              classname, totalMethods, paramaters, members, constructors, numFields);
    } catch (ClassNotFoundException e) {
      e.printStackTrace(); // will never be reached if recursion is done
    }

    return ret;
  }
  private static void print(Class<?> clazz) {

    if (WarpCommons.debugMode()) {

      System.out.println();
      System.out.println("Class: " + clazz.getName());
      System.out.println(
          "SuperClass: " + clazz.getSuperclass() + " " + clazz.getSuperclass().hashCode());
      System.out.println("Interfaces: " + Arrays.asList(clazz.getInterfaces()));
      System.out.println("Fields");
      for (Field field : clazz.getDeclaredFields()) {
        printAnnotation(field);
        System.out.println("\t" + field);
      }

      System.out.println("Constructors");
      for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        printAnnotation(constructor);
        System.out.println("\t" + constructor);
      }

      System.out.println("Methods");
      for (Method method : clazz.getDeclaredMethods()) {
        printAnnotation(method);
        System.out.println("\t" + method);
      }
    }
  }
 private static <T> T getInstance(Class<T> clazz)
     throws InstantiationException, IllegalAccessException, NoSuchMethodException,
         SecurityException, IllegalArgumentException, InvocationTargetException {
   Constructor<T> constructor = (Constructor<T>) clazz.getDeclaredConstructors()[0];
   constructor.setAccessible(true);
   return constructor.newInstance(null);
 }