示例#1
0
 @SuppressWarnings("unchecked")
 public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... paramTypes) {
   Constructor<T>[] ctors = (Constructor<T>[]) type.getConstructors();
   for (Constructor<T> ctor : ctors)
     if (typesMatch(paramTypes, ctor.getParameterTypes())) return ctor;
   return null;
 }
 @NotNull
 private static Stream<Constructor<?>> candidateConstructorsSortedByDescendingParameterCount(
     @NotNull Class<?> cl) {
   return Stream.of(cl.getConstructors())
       .filter(ctor -> !ctor.isAnnotationPresent(DalesbredIgnore.class))
       .sorted(comparing((Constructor<?> ctor) -> ctor.getParameterTypes().length).reversed());
 }
示例#3
0
 private static Constructor fullConstructor(Class klass) {
   Constructor[] array = klass.getConstructors();
   for (Constructor constructor : array) {
     if (constructor.isAnnotationPresent(FullConstructor.class)) {
       return constructor;
     }
   }
   return null;
 }
示例#4
0
  @SuppressWarnings("unchecked")
  private <T> T getDefaultInternal(
      Class<T> type, List<InstanceProvider> providers, int recursionLevel) {

    // Guard against recursion
    if (recursionLevel > MAXIMUM_RECURSION) {
      return null;
    }

    for (InstanceProvider generator : providers) {
      Object value = generator.create(type);

      if (value != null) return (T) value;
    }

    Constructor<T> minimum = null;
    int lastCount = Integer.MAX_VALUE;

    // Find the constructor with the fewest parameters
    for (Constructor<?> candidate : type.getConstructors()) {
      Class<?>[] types = candidate.getParameterTypes();

      // Note that we don't allow recursive types - that is, types that
      // require itself in the constructor.
      if (types.length < lastCount) {
        if (!contains(types, type)) {
          minimum = (Constructor<T>) candidate;
          lastCount = types.length;

          // Don't loop again if we've already found the best possible constructor
          if (lastCount == 0) break;
        }
      }
    }

    // Create the type with this constructor using default values. This might fail, though.
    try {
      if (minimum != null) {
        Object[] params = new Object[lastCount];
        Class<?>[] types = minimum.getParameterTypes();

        // Fill out
        for (int i = 0; i < lastCount; i++) {
          params[i] = getDefaultInternal(types[i], providers, recursionLevel + 1);
        }

        return createInstance(type, minimum, types, params);
      }

    } catch (Exception e) {
      // Nope, we couldn't create this type
    }

    // No suitable default value could be found
    return null;
  }
示例#5
0
  /**
   * Check if the class has a default constructor.
   *
   * @param cls
   * @return true if the type has default constructor, false if not.
   */
  public static boolean hasDefaultConstructor(Class cls) {

    Constructor[] constructors = cls.getConstructors();

    // go through all the constructors trying to find one with no
    // parameters
    for (Constructor constructor : constructors) {
      if (constructor.getParameterTypes().length == 0) {
        return true;
      }
    }
    return false;
  }
  @SuppressWarnings("unchecked")
  private static <T> Constructor<T> getConstructor(Class<T> type) {
    try {
      return type.getDeclaredConstructor();
    } catch (NoSuchMethodException e) {
      // Ignore
    }

    Constructor[] constructors = type.getConstructors();
    if (constructors.length != 1) {
      throw new IllegalStateException("Class " + type + " should have a single public constructor");
    }

    return constructors[0];
  }
示例#7
0
 /**
  * Finds the constructor of the given class that is compatible with the given arguments.
  *
  * @param type the class to find the constructor of
  * @param args the arguments
  * @return the constructor
  */
 public static Constructor findConstructor(Class<?> type, Object[] args) {
   outer:
   for (Constructor constructor : type.getConstructors()) {
     Class<?>[] paramTypes = constructor.getParameterTypes();
     if (paramTypes.length != args.length) continue;
     for (int i = 0; i < args.length; i++) {
       Object arg = args[i];
       if (arg != null && !paramTypes[i].isAssignableFrom(arg.getClass())) continue outer;
       if (arg == null && paramTypes[i].isPrimitive()) continue outer;
     }
     return constructor;
   }
   throw new GrammarException(
       "No constructor found for %s and the given %s arguments", type, args.length);
 }
  private static Object createArgumentPlaceholderForUnknownClass(
      Class<?> clazz, Integer placeholderId) throws IllegalAccessException, InstantiationException {
    FinalClassArgumentCreator<?> creator = FINAL_CLASS_ARGUMENT_CREATORS.get(clazz);
    if (creator != null) return creator.createArgumentPlaceHolder(placeholderId);

    for (Constructor constructor : clazz.getConstructors()) {
      Class<?>[] params = constructor.getParameterTypes();
      if (params.length != 1) continue;
      try {
        if (params[0] == String.class)
          return constructor.newInstance(String.valueOf(placeholderId));
        if (isNumericClass(params[0])) return constructor.newInstance(placeholderId);
      } catch (IllegalAccessException e1) {
      } catch (InvocationTargetException e2) {
      }
    }
    return clazz.newInstance();
  }
  public ConstructorArgumentConverter(Class<T> clazz, Object... arguments) {
    for (Constructor<?> c : clazz.getConstructors()) {
      if (isCompatible(c, arguments)) {
        this.constructor = (Constructor<T>) c;
        break;
      }
    }

    if (constructor == null)
      throw new IntrospectionException(
          "Unable to find a constructor of "
              + clazz.getName()
              + " compatible with the given arguments");

    if (arguments != null)
      for (Object argument : arguments) {
        argumentConverters.add(new ArgumentConverter<F, Object>(argument));
      }
  }
示例#10
0
  public static Entity createEntity(String name, FullChunk chunk, CompoundTag nbt, Object... args) {
    Entity entity = null;

    if (knownEntities.containsKey(name)) {
      Class<? extends Entity> clazz = knownEntities.get(name);

      if (clazz == null) {
        return null;
      }

      for (Constructor constructor : clazz.getConstructors()) {
        if (entity != null) {
          break;
        }

        if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) {
          continue;
        }

        try {
          if (args == null || args.length == 0) {
            entity = (Entity) constructor.newInstance(chunk, nbt);
          } else {
            Object[] objects = new Object[args.length + 2];

            objects[0] = chunk;
            objects[1] = nbt;
            System.arraycopy(args, 0, objects, 2, args.length);
            entity = (Entity) constructor.newInstance(objects);
          }
        } catch (Exception e) {
          // ignore
        }
      }
    }

    return entity;
  }
  /**
   * Read Node config from file config.nodeConfigFileName, including available nodes and their
   * possible connections
   */
  public NodeFactory(Config config, ProblemData problemData) {
    this.config = config;
    this.problemData = problemData;
    try {
      FileInputStream in = new FileInputStream(config.nodeConfigFileName);
      Properties props = new Properties();
      props.load(in);
      in.close();

      String separator = "\\s*,\\s*";

      String tmp = props.getProperty("sets");
      String[] sets = tmp.split(separator);

      nodeSets = new NodeSet[sets.length];

      int i, j, k;
      for (i = 0; i < sets.length; i++) {
        nodeSets[i] = new NodeSet(sets[i]);
        String[] nodes;
        tmp = props.getProperty(sets[i] + "Functions");
        if (tmp == null)
          Logger.log(
              "Warning: when reading "
                  + config.nodeConfigFileName
                  + ", no functions found for set "
                  + sets[i]);
        else {
          nodes = tmp.split(separator);
          for (j = 0; j < nodes.length; j++) {
            Class cl = Class.forName("gpalta.nodes." + nodes[j]);
            java.lang.reflect.Constructor co = cl.getConstructor();
            nodeSets[i].addFunction((Node) co.newInstance());
          }
        }
        tmp = props.getProperty(sets[i] + "Terminals");
        if (tmp == null)
          Logger.log(
              "Warning: when reading "
                  + config.nodeConfigFileName
                  + ", no terminals found for set "
                  + sets[i]);
        else {
          nodes = tmp.split(separator);
          for (j = 0; j < nodes.length; j++) {
            Class cl = Class.forName("gpalta.nodes." + nodes[j]);
            if (nodes[j].contains("Var")) {
              for (k = 0; k < problemData.nVars; k++) {
                java.lang.reflect.Constructor[] co = cl.getConstructors();
                nodeSets[i].addTerminal((Node) co[0].newInstance(k + 1));
              }
            } else if (nodes[j].contains("Angle")) {
              for (k = 0; k < problemData.nVars - 1; k++) {
                java.lang.reflect.Constructor[] co = cl.getConstructors();
                nodeSets[i].addTerminal((Node) co[0].newInstance(k + 1));
              }
            } else {
              java.lang.reflect.Constructor co = cl.getConstructor();
              nodeSets[i].addTerminal((Node) co.newInstance());
            }
          }
        }
      }

      for (i = 0; i < nodeSets.length; i++) {
        for (Node n : nodeSets[i].getAll()) {
          n.setType(nodeSets[i]);
        }
      }

      for (i = 0; i < nodeSets.length; i++) {
        for (Node n : nodeSets[i].getAll()) {
          tmp = props.getProperty("kids" + n.getClass().getSimpleName());
          if (tmp != null) {
            String[] kids = tmp.split(separator);
            if (kids.length != n.nKids()) {
              Logger.log(
                  "Error reading "
                      + config.nodeConfigFileName
                      + ": must specify "
                      + n.nKids()
                      + " kids for "
                      + n.getClass().getSimpleName());
            }
            for (j = 0; j < n.nKids(); j++) {
              for (k = 0; k < nodeSets.length; k++) {
                if (nodeSets[k].getName().equals(kids[j])) {
                  n.setTypeOfKids(j, nodeSets[k]);
                  break;
                }
              }
              if (k == nodeSets.length)
                Logger.log(
                    "Error reading "
                        + config.nodeConfigFileName
                        + ": Setting kids for "
                        + n.getClass().getSimpleName()
                        + ", "
                        + kids[j]
                        + " doesn't match any set name");
            }
          } else for (j = 0; j < n.nKids(); j++) n.setTypeOfKids(j, nodeSets[i]);
        }
      }
      tmp = props.getProperty("treeRoot");
      if (tmp == null) {
        Logger.log(
            "Error reading " + config.nodeConfigFileName + ": property \"treeRoot\" not present");
      }
      for (i = 0; i < nodeSets.length; i++) {
        if (nodeSets[i].getName().equals(tmp)) {
          treeRoot = nodeSets[i];
          break;
        }
      }
      if (i == nodeSets.length)
        Logger.log(
            "Error reading "
                + config.nodeConfigFileName
                + ": Setting treeRoot, "
                + tmp
                + " doesn't match any set name");
    } catch (IOException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (ClassNotFoundException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (NoSuchMethodException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (InstantiationException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (IllegalAccessException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    } catch (InvocationTargetException e) {
      Logger.log("Error reading " + config.nodeConfigFileName + ":");
      Logger.log(e);
    }
  }
示例#12
0
  public static byte[] createAdapterCode(
      ObjToIntMap functionNames,
      String adapterName,
      Class<?> superClass,
      Class<?>[] interfaces,
      String scriptClassName) {
    ClassFileWriter cfw = new ClassFileWriter(adapterName, superClass.getName(), "<adapter>");
    cfw.addField(
        "factory",
        "Laurora/javascript/ContextFactory;",
        (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL));
    cfw.addField(
        "delegee",
        "Laurora/javascript/Scriptable;",
        (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL));
    cfw.addField(
        "self",
        "Laurora/javascript/Scriptable;",
        (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL));
    int interfacesCount = interfaces == null ? 0 : interfaces.length;
    for (int i = 0; i < interfacesCount; i++) {
      if (interfaces[i] != null) cfw.addInterface(interfaces[i].getName());
    }

    String superName = superClass.getName().replace('.', '/');
    Constructor<?>[] ctors = superClass.getConstructors();
    for (Constructor<?> ctor : ctors) {
      generateCtor(cfw, adapterName, superName, ctor);
    }
    generateSerialCtor(cfw, adapterName, superName);
    if (scriptClassName != null) {
      generateEmptyCtor(cfw, adapterName, superName, scriptClassName);
    }

    ObjToIntMap generatedOverrides = new ObjToIntMap();
    ObjToIntMap generatedMethods = new ObjToIntMap();

    // generate methods to satisfy all specified interfaces.
    for (int i = 0; i < interfacesCount; i++) {
      Method[] methods = interfaces[i].getMethods();
      for (int j = 0; j < methods.length; j++) {
        Method method = methods[j];
        int mods = method.getModifiers();
        if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) {
          continue;
        }
        String methodName = method.getName();
        Class<?>[] argTypes = method.getParameterTypes();
        if (!functionNames.has(methodName)) {
          try {
            superClass.getMethod(methodName, argTypes);
            // The class we're extending implements this method and
            // the JavaScript object doesn't have an override. See
            // bug 61226.
            continue;
          } catch (NoSuchMethodException e) {
            // Not implemented by superclass; fall through
          }
        }
        // make sure to generate only one instance of a particular
        // method/signature.
        String methodSignature = getMethodSignature(method, argTypes);
        String methodKey = methodName + methodSignature;
        if (!generatedOverrides.has(methodKey)) {
          generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true);
          generatedOverrides.put(methodKey, 0);
          generatedMethods.put(methodName, 0);
        }
      }
    }

    // Now, go through the superclass's methods, checking for abstract
    // methods or additional methods to override.

    // generate any additional overrides that the object might contain.
    Method[] methods = getOverridableMethods(superClass);
    for (int j = 0; j < methods.length; j++) {
      Method method = methods[j];
      int mods = method.getModifiers();
      // if a method is marked abstract, must implement it or the
      // resulting class won't be instantiable. otherwise, if the object
      // has a property of the same name, then an override is intended.
      boolean isAbstractMethod = Modifier.isAbstract(mods);
      String methodName = method.getName();
      if (isAbstractMethod || functionNames.has(methodName)) {
        // make sure to generate only one instance of a particular
        // method/signature.
        Class<?>[] argTypes = method.getParameterTypes();
        String methodSignature = getMethodSignature(method, argTypes);
        String methodKey = methodName + methodSignature;
        if (!generatedOverrides.has(methodKey)) {
          generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true);
          generatedOverrides.put(methodKey, 0);
          generatedMethods.put(methodName, 0);

          // if a method was overridden, generate a "super$method"
          // which lets the delegate call the superclass' version.
          if (!isAbstractMethod) {
            generateSuper(
                cfw,
                adapterName,
                superName,
                methodName,
                methodSignature,
                argTypes,
                method.getReturnType());
          }
        }
      }
    }

    // Generate Java methods for remaining properties that are not
    // overrides.
    ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames);
    for (iter.start(); !iter.done(); iter.next()) {
      String functionName = (String) iter.getKey();
      if (generatedMethods.has(functionName)) continue;
      int length = iter.getValue();
      Class<?>[] parms = new Class[length];
      for (int k = 0; k < length; k++) parms[k] = ScriptRuntime.ObjectClass;
      generateMethod(cfw, adapterName, functionName, parms, ScriptRuntime.ObjectClass, false);
    }
    return cfw.toByteArray();
  }
示例#13
0
 @SuppressWarnings({"unchecked", "rawtypes"})
 public static <T> T newInstance(Class<T> type, boolean strict, Object... parameters) {
   if (parameters.length == 0) return newInstanceFromDefaultConstructor(type);
   Constructor<T> constructorToUse = null;
   try {
     Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors();
     List<Constructor<T>> candidates = new ArrayList<Constructor<T>>(constructors.length);
     int paramCount = parameters.length;
     for (Constructor<T> constructor : constructors)
       if (constructor.getParameterTypes().length == paramCount) candidates.add(constructor);
     if (candidates.size() == 1) constructorToUse = candidates.get(0);
     else if (candidates.size() == 0)
       throw new ConfigurationError(
           "No constructor with " + paramCount + " parameters found for " + type);
     else {
       // there are several candidates - find the first one with matching types
       Class<?>[] paramTypes = new Class[parameters.length];
       for (int i = 0; i < parameters.length; i++) paramTypes[i] = parameters[i].getClass();
       for (Constructor c : type.getConstructors()) {
         if (typesMatch(c.getParameterTypes(), paramTypes)) {
           constructorToUse = c;
           break;
         }
       }
       // there is no ideal match
       if (constructorToUse == null) {
         if (strict)
           throw new NoSuchMethodException(
               "No appropriate constructor found: "
                   + type
                   + '('
                   + ArrayFormat.format(", ", paramTypes)
                   + ')');
         Exception mostRecentException = null;
         for (Constructor<T> candidate : candidates) {
           try {
             return newInstance(candidate, strict, parameters);
           } catch (Exception e) {
             mostRecentException = e;
             logger.warn("Exception in constructor call: " + candidate, e);
             continue; // ignore exception and try next constructor
           }
         }
         // no constructor could be called without exception
         String errMsg =
             (mostRecentException != null
                 ? "None of these constructors could be called without exception: "
                     + candidates
                     + ", latest exception: "
                     + mostRecentException
                 : type
                     + " has no appropriate constructor for the arguments "
                     + ArrayFormat.format(", ", parameters));
         throw new ConfigurationError(errMsg);
       }
     }
     if (!strict) parameters = convertArray(parameters, constructorToUse.getParameterTypes());
     return newInstance(constructorToUse, parameters);
   } catch (SecurityException e) {
     throw ExceptionMapper.configurationException(e, constructorToUse);
   } catch (NoSuchMethodException e) {
     throw ExceptionMapper.configurationException(e, type);
   }
 }
示例#14
0
  private <T> Class<? extends T> generateUnderLock(Class<T> type) {
    Map<Class<?>, Class<?>> cache = GENERATED_CLASSES.get(getClass());
    if (cache == null) {
      // WeakHashMap won't work here. It keeps a strong reference to the mapping value, which is the
      // generated class in this case
      // However, the generated class has a strong reference to the source class (by extending it),
      // so the keys will always be
      // strongly reachable while this Class is strongly reachable. Use weak references for both key
      // and value of the mapping instead.
      cache = new ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK);
      GENERATED_CLASSES.put(getClass(), cache);
    }
    Class<?> generatedClass = cache.get(type);
    if (generatedClass != null) {
      return generatedClass.asSubclass(type);
    }

    if (Modifier.isPrivate(type.getModifiers())) {
      throw new GradleException(
          String.format(
              "Cannot create a proxy class for private class '%s'.", type.getSimpleName()));
    }
    if (Modifier.isAbstract(type.getModifiers())) {
      throw new GradleException(
          String.format(
              "Cannot create a proxy class for abstract class '%s'.", type.getSimpleName()));
    }

    Class<? extends T> subclass;
    try {
      ClassMetaData classMetaData = inspectType(type);

      ClassBuilder<T> builder = start(type, classMetaData);

      builder.startClass();

      if (!DynamicObjectAware.class.isAssignableFrom(type)) {
        if (ExtensionAware.class.isAssignableFrom(type)) {
          throw new UnsupportedOperationException(
              "A type that implements ExtensionAware must currently also implement DynamicObjectAware.");
        }
        builder.mixInDynamicAware();
      }
      if (!GroovyObject.class.isAssignableFrom(type)) {
        builder.mixInGroovyObject();
      }
      builder.addDynamicMethods();
      if (classMetaData.conventionAware && !IConventionAware.class.isAssignableFrom(type)) {
        builder.mixInConventionAware();
      }

      Class noMappingClass = Object.class;
      for (Class<?> c = type; c != null && noMappingClass == Object.class; c = c.getSuperclass()) {
        if (c.getAnnotation(NoConventionMapping.class) != null) {
          noMappingClass = c;
        }
      }

      Set<PropertyMetaData> conventionProperties = new HashSet<PropertyMetaData>();

      for (PropertyMetaData property : classMetaData.properties.values()) {
        if (SKIP_PROPERTIES.contains(property.name)) {
          continue;
        }

        if (property.injector) {
          builder.addInjectorProperty(property);
          for (Method getter : property.getters) {
            builder.applyServiceInjectionToGetter(property, getter);
          }
          for (Method setter : property.setters) {
            builder.applyServiceInjectionToSetter(property, setter);
          }
          continue;
        }

        boolean needsConventionMapping = false;
        if (classMetaData.isExtensible()) {
          for (Method getter : property.getters) {
            if (!Modifier.isFinal(getter.getModifiers())
                && !getter.getDeclaringClass().isAssignableFrom(noMappingClass)) {
              needsConventionMapping = true;
              break;
            }
          }
        }

        if (needsConventionMapping) {
          conventionProperties.add(property);
          builder.addConventionProperty(property);
          for (Method getter : property.getters) {
            builder.applyConventionMappingToGetter(property, getter);
          }
        }

        if (needsConventionMapping) {
          for (Method setter : property.setters) {
            if (!Modifier.isFinal(setter.getModifiers())) {
              builder.applyConventionMappingToSetter(property, setter);
            }
          }
        }
      }

      Set<Method> actionMethods = classMetaData.missingOverloads;
      for (Method method : actionMethods) {
        builder.addActionMethod(method);
      }

      // Adds a set method for each mutable property
      for (PropertyMetaData property : classMetaData.properties.values()) {
        if (property.setters.isEmpty()) {
          continue;
        }
        if (Iterable.class.isAssignableFrom(property.getType())) {
          // Currently not supported
          continue;
        }

        if (property.setMethods.isEmpty()) {
          for (Method setter : property.setters) {
            builder.addSetMethod(property, setter);
          }
        } else if (conventionProperties.contains(property)) {
          for (Method setMethod : property.setMethods) {
            builder.applyConventionMappingToSetMethod(property, setMethod);
          }
        }
      }

      for (Constructor<?> constructor : type.getConstructors()) {
        if (Modifier.isPublic(constructor.getModifiers())) {
          builder.addConstructor(constructor);
        }
      }

      subclass = builder.generate();
    } catch (Throwable e) {
      throw new GradleException(
          String.format("Could not generate a proxy class for class %s.", type.getName()), e);
    }

    cache.put(type, subclass);
    cache.put(subclass, subclass);
    return subclass;
  }