/**
   * 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);
  }
Ejemplo n.º 2
0
  protected void _addConstructorMixIns(Class<?> mixin) {
    MemberKey[] ctorKeys = null;
    int ctorCount = (_constructors == null) ? 0 : _constructors.size();
    for (Constructor<?> ctor : mixin.getDeclaredConstructors()) {
      switch (ctor.getParameterTypes().length) {
        case 0:
          if (_defaultConstructor != null) {
            _addMixOvers(ctor, _defaultConstructor, false);
          }
          break;
        default:
          if (ctorKeys == null) {
            ctorKeys = new MemberKey[ctorCount];
            for (int i = 0; i < ctorCount; ++i) {
              ctorKeys[i] = new MemberKey(_constructors.get(i).getAnnotated());
            }
          }
          MemberKey key = new MemberKey(ctor);

          for (int i = 0; i < ctorCount; ++i) {
            if (!key.equals(ctorKeys[i])) {
              continue;
            }
            _addMixOvers(ctor, _constructors.get(i), true);
            break;
          }
      }
    }
  }
Ejemplo n.º 3
0
  public Constructor[] getAllConstructorsFromClass(Class c) {

    Constructor[] cList;

    cList = c.getDeclaredConstructors();
    return cList;
  }
Ejemplo n.º 4
0
  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.");
      }
    }
  }
 public void apply()
     throws IllegalAccessException, InvocationTargetException, InstantiationException {
   if (type.isEnum()) {
     for (T instance : type.getEnumConstants()) {
       assertThat(
           instance.toString(),
           is(
               type.getCanonicalName().substring(type.getPackage().getName().length() + 1)
                   + "."
                   + ((Enum<?>) instance).name()));
     }
     return;
   }
   for (Constructor<?> constructor : type.getDeclaredConstructors()) {
     if (constructor.isSynthetic() && skipSynthetic) {
       continue;
     }
     constructor.setAccessible(true);
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     Object[] actualArguments = new Object[parameterTypes.length];
     Object[] otherArguments = new Object[parameterTypes.length];
     int index = 0;
     for (Class<?> parameterType : parameterTypes) {
       putInstance(parameterType, actualArguments, otherArguments, index++);
     }
     int testIndex = 0;
     @SuppressWarnings("unchecked")
     T instance = (T) constructor.newInstance(actualArguments);
     assertThat(instance, is(instance));
     assertThat(instance, not(is((Object) null)));
     assertThat(instance, not(is(new Object())));
     Object similarInstance = constructor.newInstance(actualArguments);
     assertThat(instance.hashCode(), is(similarInstance.hashCode()));
     assertThat(instance, is(similarInstance));
     if (skipToString) {
       assertThat(instance.toString(), notNullValue());
     } else if (optionalToStringRegex == null) {
       checkString(instance);
     } else {
       assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex));
     }
     for (Object otherArgument : otherArguments) {
       Object[] compareArguments = new Object[actualArguments.length];
       int argumentIndex = 0;
       for (Object actualArgument : actualArguments) {
         if (argumentIndex == testIndex) {
           compareArguments[argumentIndex] = otherArgument;
         } else {
           compareArguments[argumentIndex] = actualArgument;
         }
         argumentIndex++;
       }
       Object unlikeInstance = constructor.newInstance(compareArguments);
       assertThat(instance.hashCode(), not(is(unlikeInstance)));
       assertThat(instance, not(is(unlikeInstance)));
       testIndex++;
     }
   }
 }
Ejemplo n.º 6
0
  /**
   * すべてのメンバを表示する
   *
   * @param Class<?> c メンバを表示したいクラス型オブジェクト
   */
  public static void printAllMembers(Class<?> c) {
    System.out.println("クラス: ");
    System.out.println(c);

    System.out.println("フィールド: ");
    Field[] declaredfields = c.getDeclaredFields();
    Field[] fields = c.getFields();
    ArrayList<Field> fieldList = new ArrayList<Field>(fields.length);
    for (int i = 0; i < fields.length; i++) {
      fieldList.add(fields[i]);
    }
    for (int i = 0; i < declaredfields.length; i++) {
      if (!fieldList.contains(declaredfields[i])) {
        fieldList.add(declaredfields[i]);
      }
    }
    Field[] allFields = new Field[fieldList.size()];
    for (int i = 0; i < allFields.length; i++) {
      allFields[i] = fieldList.get(i);
    }
    printMembers(allFields);

    System.out.println("コンストラクタ: ");
    Constructor[] declaredconstructors = c.getDeclaredConstructors();
    Constructor[] constructors = c.getConstructors();
    ArrayList<Constructor> constructorList = new ArrayList<Constructor>(constructors.length);
    for (int i = 0; i < constructors.length; i++) {
      constructorList.add(constructors[i]);
    }
    for (int i = 0; i < declaredconstructors.length; i++) {
      if (!constructorList.contains(declaredconstructors[i])) {
        constructorList.add(declaredconstructors[i]);
      }
    }
    Constructor[] allConstructors = new Constructor[constructorList.size()];
    for (int i = 0; i < allConstructors.length; i++) {
      allConstructors[i] = constructorList.get(i);
    }
    printMembers(allConstructors);

    System.out.println("メソッド: ");
    Method[] declaredmethods = c.getDeclaredMethods();
    Method[] methods = c.getMethods();
    ArrayList<Method> methodList = new ArrayList<Method>(methods.length);
    for (int i = 0; i < methods.length; i++) {
      methodList.add(methods[i]);
    }
    for (int i = 0; i < declaredmethods.length; i++) {
      if (!methodList.contains(declaredmethods[i])) {
        methodList.add(declaredmethods[i]);
      }
    }
    Method[] allMethods = new Method[methodList.size()];
    for (int i = 0; i < allMethods.length; i++) {
      allMethods[i] = methodList.get(i);
    }
    printMembers(allMethods);
  }
 public static void initializeClass(final Class<?> theClass) {
   final Constructor<?>[] cons = theClass.getDeclaredConstructors();
   if (cons != null && cons.length > 0 && cons[0] != null) {
     final String[] strs = new String[256];
     try {
       cons[0].newInstance((Object[]) strs);
     } catch (Exception ex) {
     }
   }
 }
Ejemplo n.º 8
0
  public static void main(String[] args) throws Exception {
    Class<ClassTest> clazz = ClassTest.class;

    System.out.println("=============================================");
    Constructor[] ctors = clazz.getDeclaredConstructors();
    System.out.println("classTest的全部构造器如下:");
    for (Constructor c : ctors) {
      System.out.println(c);
    }

    System.out.println("=============================================");
    Constructor[] publicCtors = clazz.getConstructors();
    System.out.println("ClassTest的全部public构造器如下:");
    for (Constructor c : publicCtors) {
      System.out.println(c);
    }

    System.out.println("=============================================");
    Method[] mtds = clazz.getMethods();
    System.out.println("ClassTest的全部public方法如下:");
    for (Method md : mtds) {
      System.out.println(md);
    }

    System.out.println("=============================================");
    System.out.println("ClassTest带一个字符串参数的info方法为:" + clazz.getMethod("info", String.class));

    Annotation[] ans = clazz.getAnnotations();
    System.out.println("ClassTest的全部annotation为:");
    for (Annotation an : ans) {
      System.out.println(an);
    }
    System.out.println("该元素上的@SuppressWarnings注释为:" + clazz.getAnnotation(SuppressWarnings.class));

    System.out.println("=============================================");
    Class<?>[] inners = clazz.getDeclaredClasses();
    System.out.println("ClassTest的全部内部类如下:");
    for (Class c : inners) {
      System.out.println(c);
    }

    System.out.println("=============================================");

    Class inClazz = Class.forName("ClassTest$Inner");
    System.out.println("inClazz对应的外部类为:" + inClazz.getDeclaringClass());
    System.out.println("ClassTest的包为:" + clazz.getPackage());
    System.out.println("ClassTest的父类:" + clazz.getSuperclass());
  }
  protected void loadClassDependencies(Class aClass) throws ClassNotFoundException {
    String name = aClass.getName();
    if (myVisited.add(aClass)) {
      try {
        for (Method method : aClass.getDeclaredMethods()) {
          loadTypeDependencies(method.getGenericReturnType());
          for (Type type : method.getGenericExceptionTypes()) {
            loadTypeDependencies(type);
          }
          for (Type type : method.getGenericParameterTypes()) {
            loadTypeDependencies(type);
          }
        }
        for (Constructor method : aClass.getDeclaredConstructors()) {
          for (Type type : method.getGenericExceptionTypes()) {
            loadTypeDependencies(type);
          }
          for (Type type : method.getGenericParameterTypes()) {
            loadTypeDependencies(type);
          }
        }

        for (Field field : aClass.getDeclaredFields()) {
          loadTypeDependencies(field.getGenericType());
        }

        Type superclass = aClass.getGenericSuperclass();
        if (superclass != null) {
          loadClassDependencies(aClass);
        }

        for (Type intf : aClass.getGenericInterfaces()) {
          loadTypeDependencies(intf);
        }

        aClass.getAnnotations();
        Package aPackage = aClass.getPackage();
        if (aPackage != null) {
          aPackage.getAnnotations();
        }
      } catch (LinkageError e) {
        throw new ClassNotFoundException(name);
      } catch (TypeNotPresentException e) {
        throw new ClassNotFoundException(name);
      }
    }
  }
Ejemplo n.º 10
0
 public static void printConstructors(Class<?> c) {
   display2.append("コンストラクタ\r\n");
   Constructor[] declaredconstructors = c.getDeclaredConstructors();
   Constructor[] constructors = c.getConstructors();
   ArrayList<Constructor> constructorList = new ArrayList<Constructor>(constructors.length);
   for (int i = 0; i < constructors.length; i++) {
     constructorList.add(constructors[i]);
   }
   for (int i = 0; i < declaredconstructors.length; i++) {
     if (!constructorList.contains(declaredconstructors[i])) {
       constructorList.add(declaredconstructors[i]);
     }
   }
   Constructor[] allConstructors = new Constructor[constructorList.size()];
   for (int i = 0; i < allConstructors.length; i++) {
     allConstructors[i] = constructorList.get(i);
   }
   printMembers(allConstructors);
 }
Ejemplo n.º 11
0
  /**
   * Prints all constructors of a class
   *
   * @param cl a class
   */
  public static void printConstructors(Class cl) {
    Constructor[] constructors = cl.getDeclaredConstructors();

    for (Constructor c : constructors) {
      String name = c.getName();
      System.out.print("   ");
      String modifiers = Modifier.toString(c.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print(name + "(");

      // print parameter types
      Class[] paramTypes = c.getParameterTypes();
      for (int j = 0; j < paramTypes.length; j++) {
        if (j > 0) System.out.print(", ");
        System.out.print(paramTypes[j].getName());
      }
      System.out.println(");");
    }
  }
Ejemplo n.º 12
0
  public void configureClassNode(CompileUnit compileUnit, ClassNode classNode) {
    Class clazz = classNode.getTypeClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field f : fields) {
      ClassNode ret = makeClassNode(compileUnit, f.getGenericType(), f.getType());
      classNode.addField(f.getName(), f.getModifiers(), ret, null);
    }
    Method[] methods = clazz.getDeclaredMethods();
    for (Method m : methods) {
      ClassNode ret = makeClassNode(compileUnit, m.getGenericReturnType(), m.getReturnType());
      Parameter[] params =
          makeParameters(compileUnit, m.getGenericParameterTypes(), m.getParameterTypes());
      ClassNode[] exceptions =
          makeClassNodes(compileUnit, m.getGenericExceptionTypes(), m.getExceptionTypes());
      MethodNode mn = new MethodNode(m.getName(), m.getModifiers(), ret, params, exceptions, null);
      setMethodDefaultValue(mn, m);
      setAnnotationMetaData(m.getAnnotations(), mn);
      mn.setGenericsTypes(configureTypeVariable(m.getTypeParameters()));
      classNode.addMethod(mn);
    }
    Constructor[] constructors = clazz.getDeclaredConstructors();
    for (Constructor ctor : constructors) {
      Parameter[] params =
          makeParameters(compileUnit, ctor.getGenericParameterTypes(), ctor.getParameterTypes());
      ClassNode[] exceptions =
          makeClassNodes(compileUnit, ctor.getGenericExceptionTypes(), ctor.getExceptionTypes());
      classNode.addConstructor(ctor.getModifiers(), params, exceptions, null);
    }

    Class sc = clazz.getSuperclass();
    if (sc != null)
      classNode.setUnresolvedSuperClass(
          makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc));
    makeInterfaceTypes(compileUnit, classNode, clazz);
    setAnnotationMetaData(classNode.getTypeClass().getAnnotations(), classNode);

    PackageNode packageNode = classNode.getPackage();
    if (packageNode != null) {
      setAnnotationMetaData(classNode.getTypeClass().getPackage().getAnnotations(), packageNode);
    }
  }
Ejemplo n.º 13
0
  /**
   * Return true if the type is not abstract and not an interface, and has a constructor annotated
   * with {@link Inject} or its only constructor is the default constructor.
   *
   * @param type A class type
   * @return True if the class type is instantiable
   */
  public static boolean isInstantiable(Class<?> type) {
    if (!Modifier.isAbstract(type.getModifiers()) && !type.isInterface()) {
      // first check for a constructor annotated with @Inject,
      //  - this doesn't care how many we'll let the injector complain
      //    if there are more than one
      for (Constructor<?> c : type.getDeclaredConstructors()) {
        if (c.getAnnotation(Inject.class) != null) {
          return true;
        }
      }

      // check if we only have the public default constructor
      if (type.getConstructors().length == 1
          && type.getConstructors()[0].getParameterTypes().length == 0) {
        return true;
      }
    }

    // no constructor available
    return false;
  }
 public void applyBasic()
     throws IllegalAccessException, InvocationTargetException, InstantiationException {
   for (Constructor<?> constructor : type.getDeclaredConstructors()) {
     if (constructor.isSynthetic() && skipSynthetic) {
       continue;
     }
     constructor.setAccessible(true);
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     Object[] actualArguments = new Object[parameterTypes.length];
     Object[] otherArguments = new Object[parameterTypes.length];
     int index = 0;
     for (Class<?> parameterType : parameterTypes) {
       putInstance(parameterType, actualArguments, otherArguments, index++);
     }
     @SuppressWarnings("unchecked")
     T instance = (T) constructor.newInstance(actualArguments);
     checkString(instance);
     assertThat(instance, is(instance));
     assertThat(instance, not(is((Object) null)));
     assertThat(instance, not(is(new Object())));
     assertThat(instance, not(is(constructor.newInstance(otherArguments))));
   }
 }
Ejemplo n.º 15
0
 /**
  * すべてのメンバを表示する
  *
  * @param Class<?> c メンバを表示したいクラス型オブジェクト
  * @param String stripped 表示を省略したい文字列
  */
 public static void printAllMembers(Class<?> c, String stripped) {
   System.out.println(c);
   printMembers(c.getDeclaredFields(), stripped);
   printMembers(c.getDeclaredConstructors(), stripped);
   printMembers(c.getDeclaredMethods(), stripped);
 }
Ejemplo n.º 16
0
  /**
   * Initialization method that will find out all constructors and potential static factory methods
   * the class has.
   *
   * <p>Starting with 1.2, it will also apply mix-in annotations, as per [JACKSON-76]
   *
   * @param includeAll If true, includes all creator methods; if false, will only include the
   *     no-arguments "default" constructor
   */
  public void resolveCreators(boolean includeAll) {
    // Then see which constructors we have
    _constructors = null;
    for (Constructor<?> ctor : _class.getDeclaredConstructors()) {
      switch (ctor.getParameterTypes().length) {
        case 0:
          _defaultConstructor = _constructConstructor(ctor, true);
          break;
        default:
          if (includeAll) {
            if (_constructors == null) {
              _constructors = new ArrayList<AnnotatedConstructor>();
            }
            _constructors.add(_constructConstructor(ctor, false));
          }
      }
    }
    // and if need be, augment with mix-ins
    if (_primaryMixIn != null) {
      if (_defaultConstructor != null || _constructors != null) {
        _addConstructorMixIns(_primaryMixIn);
      }
    }

    /* And then... let's remove all constructors that are
     * deemed to be ignorable after all annotations have been
     * properly collapsed.
     */
    if (_defaultConstructor != null) {
      if (_annotationIntrospector.isIgnorableConstructor(_defaultConstructor)) {
        _defaultConstructor = null;
      }
    }
    if (_constructors != null) {
      // count down to allow safe removal
      for (int i = _constructors.size(); --i >= 0; ) {
        if (_annotationIntrospector.isIgnorableConstructor(_constructors.get(i))) {
          _constructors.remove(i);
        }
      }
    }

    _creatorMethods = null;

    if (includeAll) {
      /* Then static methods which are potential factory
       * methods
       */
      for (Method m : _class.getDeclaredMethods()) {
        if (!Modifier.isStatic(m.getModifiers())) {
          continue;
        }
        int argCount = m.getParameterTypes().length;
        // factory methods take at least one arg:
        if (argCount < 1) {
          continue;
        }
        if (_creatorMethods == null) {
          _creatorMethods = new ArrayList<AnnotatedMethod>();
        }
        _creatorMethods.add(_constructCreatorMethod(m));
      }
      // mix-ins to mix in?
      if (_primaryMixIn != null && _creatorMethods != null) {
        _addFactoryMixIns(_primaryMixIn);
      }
      // anything to ignore at this point?
      if (_creatorMethods != null) {
        // count down to allow safe removal
        for (int i = _creatorMethods.size(); --i >= 0; ) {
          if (_annotationIntrospector.isIgnorableMethod(_creatorMethods.get(i))) {
            _creatorMethods.remove(i);
          }
        }
      }
    }
  }