예제 #1
1
  private static RetryPolicy instantiateRetryPolicy(
      String policyClassName, Object[] args, String raw) throws Exception {

    Class<?> policyClass = Class.forName(policyClassName);

    for (Constructor<?> con : policyClass.getConstructors()) {
      Class<?>[] parameterClasses = con.getParameterTypes();
      if (args.length == parameterClasses.length) {
        boolean allInts = true;
        for (Class<?> pc : parameterClasses) {
          if (!pc.equals(int.class)) {
            allInts = false;
            break;
          }
        }

        if (!allInts) {
          break;
        }

        log.debug("About to instantiate class {} with {} arguments", con.toString(), args.length);

        return (RetryPolicy) con.newInstance(args);
      }
    }

    throw new Exception(
        "Failed to identify a class matching the Astyanax Retry Policy config string \""
            + raw
            + "\"");
  }
예제 #2
1
 protected <T> Constructor<T> findMatchingCtor(Class<T> clazz, Object... args) {
   List<Constructor> ctors = new ArrayList<Constructor>();
   for (Constructor ct : clazz.getConstructors()) {
     if (isCompatible(ct.getParameterTypes(), args)) {
       ctors.add(ct);
     }
   }
   if (ctors.isEmpty()) {
     return null;
   }
   Collections.sort(
       ctors,
       new Comparator<Constructor>() {
         @Override
         public int compare(Constructor o1, Constructor o2) {
           int sum = 0;
           for (Class c0 : o1.getParameterTypes()) {
             for (Class c1 : o2.getParameterTypes()) {
               sum += classDist(c0, c1);
             }
           }
           return sum;
         }
       });
   //noinspection unchecked
   return ctors.get(0);
 }
예제 #3
0
        @Override
        public int compare(Constructor<?> o1, Constructor<?> o2) {
          int p1 = o1.getParameterTypes().length;
          int p2 = o2.getParameterTypes().length;

          return (p1 < p2) ? 1 : ((p1 == p2) ? 0 : -1);
        }
  /**
   * 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);
  }
예제 #5
0
  /**
   * Compare two constructors. These constructors must be known to match using the <code>matches()
   * </code> method in order to be compared.
   *
   * <p>The general idea is to look at each argument and see if it can be cast to the comparable
   * argument of the other class. The goal is to find a constructor that is <i>more specific</i>
   * than another constructor. A constructor is more specific than another iff all its parameter
   * types are assignable to the type of the other constructor, but not vice versa. For example if
   * one constructor takes a String argument and another takes an Object, the one that takes the
   * String is more specific because String can be cast to Object, but not vice-versa.
   *
   * <p>If some arguments of one constructor are more specific and some arguments of the other are
   * more specific, the constructors are equally specific.
   *
   * <p>This method compares two constructors, and returns 1 if the first constructor is more
   * specific than the second, 0 if they are equally specific and -1 if the second constructor is
   * more specific than the first.
   *
   * @param c0 the first constructor
   * @param c1 the second constructor
   * @return 1 if c0 is more specific than c1, 0 if they are equally specific and -1 if c1 is more
   *     specific than c0.
   */
  public int compare(Constructor c0, Constructor c1) {
    Class<?>[] c0Params = c0.getParameterTypes();
    Class<?>[] c1Params = c1.getParameterTypes();

    // counts of more or less specific arguments
    int moreCount = 0;
    int lessCount = 0;

    for (int i = 0; i < c0Params.length; i++) {
      boolean more = c1Params[i].isAssignableFrom(c0Params[i]);
      boolean less = c0Params[i].isAssignableFrom(c1Params[i]);

      if (more && !less) {
        moreCount++;
      } else if (less && !more) {
        lessCount++;
      }
    }

    if (moreCount > 0 && lessCount == 0) {
      return 1;
    } else if (lessCount > 0 && moreCount == 0) {
      return -1;
    } else {
      return 0;
    }
  }
예제 #6
0
 public static JoinPoint.StaticPart makeEncSJP(Member member) {
   Signature sig = null;
   String kind = null;
   if (member instanceof Method) {
     Method method = (Method) member;
     sig =
         new MethodSignatureImpl(
             method.getModifiers(),
             method.getName(),
             method.getDeclaringClass(),
             method.getParameterTypes(),
             new String[method.getParameterTypes().length],
             method.getExceptionTypes(),
             method.getReturnType());
     kind = JoinPoint.METHOD_EXECUTION;
   } else if (member instanceof Constructor) {
     Constructor cons = (Constructor) member;
     sig =
         new ConstructorSignatureImpl(
             cons.getModifiers(),
             cons.getDeclaringClass(),
             cons.getParameterTypes(),
             new String[cons.getParameterTypes().length],
             cons.getExceptionTypes());
     kind = JoinPoint.CONSTRUCTOR_EXECUTION;
   } else {
     throw new IllegalArgumentException("member must be either a method or constructor");
   }
   return new JoinPointImpl.EnclosingStaticPartImpl(-1, kind, sig, null);
 }
예제 #7
0
 /**
  * Find an accessible constructor with compatible parameters. Compatible parameters mean that
  * every method parameter is assignable from the given parameters. In other words, it finds
  * constructor that will take the parameters given.
  *
  * <p>First it checks if there is constructor matching the exact signature. If no such, all the
  * constructors of the class are tested if their signatures are assignment compatible with the
  * parameter types. The first matching constructor is returned.
  *
  * @param cls find constructor for this class
  * @param parameterTypes find method with compatible parameters
  * @return a valid Constructor object. If there's no matching constructor, returns <code>null
  *     </code>.
  */
 public static Constructor getMatchingAccessibleConstructor(Class cls, Class[] parameterTypes) {
   // see if we can find the constructor directly
   // most of the time this works and it's much faster
   try {
     Constructor ctor = cls.getConstructor(parameterTypes);
     MemberUtils.setAccessibleWorkaround(ctor);
     return ctor;
   } catch (NoSuchMethodException e) {
     /* SWALLOW */
   }
   Constructor result = null;
   // search through all constructors
   Constructor[] ctors = cls.getConstructors();
   for (int i = 0; i < ctors.length; i++) {
     // compare parameters
     if (ClassUtils.isAssignable(parameterTypes, ctors[i].getParameterTypes(), true)) {
       // get accessible version of method
       Constructor ctor = getAccessibleConstructor(ctors[i]);
       if (ctor != null) {
         MemberUtils.setAccessibleWorkaround(ctor);
         if (result == null
             || MemberUtils.compareParameterTypes(
                     ctor.getParameterTypes(), result.getParameterTypes(), parameterTypes)
                 < 0) {
           result = ctor;
         }
       }
     }
   }
   return result;
 }
예제 #8
0
 @Test
 public void testGetExceptionConstructorFindStringConstructor() {
   Constructor<?> constructor = new ExceptionFactory().getExceptionConstructor(Exception.class);
   assertThat(constructor, not(nullValue()));
   assertThat(constructor.getParameterTypes().length, equalTo(1));
   Class<?> parameterType = constructor.getParameterTypes()[0];
   assertThat(parameterType.equals(String.class), equalTo(true));
 }
 public FindConstructorParameterNamesClassVisitor(Constructor ctor) {
   super("<init>", false, ctor.getParameterTypes());
   Type[] pTypes = new Type[ctor.getParameterTypes().length];
   for (int i = 0; i < pTypes.length; i++) {
     pTypes[i] = Type.getType(ctor.getParameterTypes()[i]);
   }
   setDescriptorToMatch(Type.getMethodDescriptor(Type.VOID_TYPE, pTypes));
 }
 @Override
 public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
     throws BeansException {
   // Quick check on the concurrent map first, with minimal locking.
   Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
   if (candidateConstructors == null) {
     synchronized (this.candidateConstructorsCache) {
       candidateConstructors = this.candidateConstructorsCache.get(beanClass);
       if (candidateConstructors == null) {
         Constructor<?>[] rawCandidates = beanClass.getDeclaredConstructors();
         List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length);
         Constructor<?> requiredConstructor = null;
         Constructor<?> defaultConstructor = null;
         for (Constructor<?> candidate : rawCandidates) {
           Annotation annotation = findAutowiredAnnotation(candidate);
           if (annotation != null) {
             if (requiredConstructor != null) {
               throw new BeanCreationException(
                   "Invalid autowire-marked constructor: "
                       + candidate
                       + ". Found another constructor with 'required' Autowired annotation: "
                       + requiredConstructor);
             }
             if (candidate.getParameterTypes().length == 0) {
               throw new IllegalStateException(
                   "Autowired annotation requires at least one argument: " + candidate);
             }
             boolean required = determineRequiredStatus(annotation);
             if (required) {
               if (!candidates.isEmpty()) {
                 throw new BeanCreationException(
                     "Invalid autowire-marked constructors: "
                         + candidates
                         + ". Found another constructor with 'required' Autowired annotation: "
                         + requiredConstructor);
               }
               requiredConstructor = candidate;
             }
             candidates.add(candidate);
           } else if (candidate.getParameterTypes().length == 0) {
             defaultConstructor = candidate;
           }
         }
         if (!candidates.isEmpty()) {
           // Add default constructor to list of optional constructors, as fallback.
           if (requiredConstructor == null && defaultConstructor != null) {
             candidates.add(defaultConstructor);
           }
           candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]);
         } else {
           candidateConstructors = new Constructor<?>[0];
         }
         this.candidateConstructorsCache.put(beanClass, candidateConstructors);
       }
     }
   }
   return (candidateConstructors.length > 0 ? candidateConstructors : null);
 }
  private static Set parseLookupBindingXml(
      UimaContext annotCtx, Map dictMap, Element lookupBindingsEl) throws Exception {

    Set lsSet = new HashSet();
    Iterator itr = lookupBindingsEl.getChildren().iterator();
    while (itr.hasNext()) {
      Element bindingEl = (Element) itr.next();

      Element dictEl = bindingEl.getChild("dictionaryRef");
      String dictID = dictEl.getAttributeValue("idRef");
      DictionaryEngine dictEngine = (DictionaryEngine) dictMap.get(dictID);
      if (dictEngine == null) {
        throw new Exception("Dictionary undefined: " + dictID);
      }

      Class[] constrArgs = {UimaContext.class, Properties.class};
      Class[] constrArgsConsum = {
        UimaContext.class, Properties.class, int.class
      }; // ohnlp-Bugs-3296301
      Class[] constrArgsConsumB = {UimaContext.class, Properties.class};

      Element lookupInitEl = bindingEl.getChild("lookupInitializer");
      String liClassName = lookupInitEl.getAttributeValue("className");
      Element liPropertiesEl = lookupInitEl.getChild("properties");
      Properties liProps = parsePropertiesXml(liPropertiesEl);
      Class liClass = Class.forName(liClassName);
      Constructor liConstr = liClass.getConstructor(constrArgs);
      Object[] liArgs = {annotCtx, liProps};
      LookupInitializer li = (LookupInitializer) liConstr.newInstance(liArgs);

      Element lookupConsumerEl = bindingEl.getChild("lookupConsumer");
      String lcClassName = lookupConsumerEl.getAttributeValue("className");
      Element lcPropertiesEl = lookupConsumerEl.getChild("properties");
      Properties lcProps = parsePropertiesXml(lcPropertiesEl);
      Class lcClass = Class.forName(lcClassName);
      Constructor[] consts = lcClass.getConstructors();
      Constructor lcConstr = null;
      Object[] lcArgs = null;
      for (int i = 0; i < consts.length; i++) {
        lcConstr = consts[i];
        if (Arrays.equals(constrArgsConsum, lcConstr.getParameterTypes())) {
          lcConstr = lcClass.getConstructor(constrArgsConsum);
          lcArgs = new Object[] {annotCtx, lcProps, maxSizeList}; // ohnlp-Bugs-3296301
        } else if (Arrays.equals(constrArgsConsumB, lcConstr.getParameterTypes())) {
          lcConstr = lcClass.getConstructor(constrArgsConsumB);
          lcArgs = new Object[] {annotCtx, lcProps};
        }
      }

      LookupConsumer lc = (LookupConsumer) lcConstr.newInstance(lcArgs);
      LookupAlgorithm la = li.getLookupAlgorithm(dictEngine);
      LookupSpec ls = new LookupSpec(la, li, lc);

      lsSet.add(ls);
    }
    return lsSet;
  }
예제 #12
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;
  }
예제 #13
0
 /**
  * Picks a constructor from an annotated resource class based on spec rules
  *
  * @param annotatedResourceClass
  * @return
  */
 public static ResourceConstructor constructor(Class<?> annotatedResourceClass) {
   Constructor constructor = PickConstructor.pickPerRequestConstructor(annotatedResourceClass);
   ResourceConstructorBuilder builder =
       resourceClass(annotatedResourceClass).constructor(constructor);
   if (constructor.getParameterTypes() != null) {
     for (int i = 0; i < constructor.getParameterTypes().length; i++)
       builder.param(i).fromAnnotations();
   }
   return builder.buildConstructor().buildClass().getConstructor();
 }
예제 #14
0
  public static Object construct(
      Class<?> klass, Object[] arguments, Map<String, Object> namedArgMap)
      throws InvocationTargetException, NoSuchMethodException {
    Objects.requireNonNull(klass, "Class cannot be null");
    Objects.requireNonNull(namedArgMap, "Named Argument Map cannot be null");

    for (Constructor<?> constructor : klass.getConstructors()) {
      if (arguments == null) {
        // null arguments in .newInstance() is allowed
        if (constructor.getParameterTypes().length != 0) continue;
      } else if (constructor.getParameterTypes().length != arguments.length) continue;

      try {
        Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();

        if (arguments == null || arguments.length == 0) {
          if (LOG.isDebugEnabled()) LOG.debug("Constructor has no arguments");
          return constructor.newInstance(arguments);
        } else if (parameterAnnotations == null || parameterAnnotations.length == 0) {
          if (LOG.isDebugEnabled()) LOG.debug("Constructor has no parameter annotations");
          return constructor.newInstance(arguments);
        } else {
          Object[] swizzled = new Object[arguments.length];

          int count = 0;
          for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
              if (annotation instanceof Name) {
                Name param = (Name) annotation;

                if (namedArgMap.containsKey(param.value())) {
                  if (LOG.isDebugEnabled())
                    LOG.debug("placing named {} in position {}", param.value(), count);
                  swizzled[count] = namedArgMap.get(param.value());
                } else {
                  if (LOG.isDebugEnabled())
                    LOG.debug("placing {} in position {}", arguments[count], count);
                  swizzled[count] = arguments[count];
                }
                ++count;
              } else {
                if (LOG.isDebugEnabled()) LOG.debug("passing on annotation {}", annotation);
              }
            }
          }

          return constructor.newInstance(swizzled);
        }

      } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
        LOG.ignore(e);
      }
    }
    throw new NoSuchMethodException("<init>");
  }
예제 #15
0
 @Test
 public void testGetCheckedConstructorReturnConstructor() {
   Constructor<?> constructor =
       new ExceptionFactory().getCheckedConstructor(Throwable.class, String.class);
   assertThat(constructor, not(nullValue()));
   Class<?> declaringClass = constructor.getDeclaringClass();
   assertThat(declaringClass.equals(Throwable.class), equalTo(true));
   assertThat(constructor.getParameterTypes().length, equalTo(1));
   Class<?> parameterType = constructor.getParameterTypes()[0];
   assertThat(parameterType.equals(String.class), equalTo(true));
 }
예제 #16
0
파일: Request2.java 프로젝트: jmcclell/h2o
 private Filter newInstance(API api) throws Exception {
   for (Constructor c : api.filter().getDeclaredConstructors()) {
     c.setAccessible(true);
     Class[] ps = c.getParameterTypes();
     if (ps.length == 1 && RequestArguments.class.isAssignableFrom(ps[0]))
       return (Filter) c.newInstance(this);
   }
   for (Constructor c : api.filter().getDeclaredConstructors()) {
     Class[] ps = c.getParameterTypes();
     if (ps.length == 0) return (Filter) c.newInstance();
   }
   throw new Exception("Class " + api.filter().getName() + " must have an empty constructor");
 }
    private void jitConstructorInvocation(ConstructorInvocation invocation) {
      Constructor constructor = invocation.getConstructor();
      Class<?> clazz = invocation.getReturnType();

      mv.visitTypeInsn(NEW, internalName(clazz));
      mv.visitInsn(DUP);

      int argumentCounter = 0;
      for (Expression argument : invocation.getArguments()) {
        cast(jitExpression(argument), constructor.getParameterTypes()[argumentCounter++]);
      }

      invokeSpecial(clazz, "<init>", null, constructor.getParameterTypes());
    }
 public ResourceConstructor(ResourceClass resourceClass, Constructor constructor) {
   this.resourceClass = resourceClass;
   this.constructor = constructor;
   if (constructor.getParameterTypes() != null) {
     this.params = new ConstructorParameter[constructor.getParameterTypes().length];
     for (int i = 0; i < constructor.getParameterTypes().length; i++) {
       this.params[i] =
           new ConstructorParameter(
               this,
               constructor.getParameterTypes()[i],
               constructor.getGenericParameterTypes()[i],
               constructor.getParameterAnnotations()[i]);
     }
   }
 }
예제 #19
0
  private MBeanConstructorInfo[] createMBeanConstructorInfo(
      MBeanMetaData metadata, MBeanDescription descrs) {
    Class mbeanClass = metadata.mbean.getClass();

    Constructor[] ctors = mbeanClass.getConstructors();
    MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[ctors.length];
    for (int i = 0; i < ctors.length; ++i) {
      Constructor constructor = ctors[i];
      String descr = descrs == null ? null : descrs.getConstructorDescription(constructor);
      Class[] params = constructor.getParameterTypes();
      MBeanParameterInfo[] paramsInfo = new MBeanParameterInfo[params.length];
      for (int j = 0; j < params.length; ++j) {
        Class param = params[j];
        String paramName =
            descrs == null ? null : descrs.getConstructorParameterName(constructor, j);
        String paramDescr =
            descrs == null ? null : descrs.getConstructorParameterDescription(constructor, j);
        paramsInfo[j] = new MBeanParameterInfo(paramName, param.getName(), paramDescr);
      }

      String ctorName = constructor.getName();
      MBeanConstructorInfo info =
          new MBeanConstructorInfo(
              ctorName.substring(ctorName.lastIndexOf('.') + 1), descr, paramsInfo);
      constructors[i] = info;
    }
    return constructors;
  }
예제 #20
0
 public static Object[] createConstructorArguments(
     Constructor<?> c, Message m, boolean perRequest, Map<Class<?>, Object> contextValues) {
   Class<?>[] params = c.getParameterTypes();
   Annotation[][] anns = c.getParameterAnnotations();
   Type[] genericTypes = c.getGenericParameterTypes();
   @SuppressWarnings("unchecked")
   MultivaluedMap<String, String> templateValues =
       m == null ? null : (MultivaluedMap<String, String>) m.get(URITemplate.TEMPLATE_PARAMETERS);
   Object[] values = new Object[params.length];
   for (int i = 0; i < params.length; i++) {
     if (AnnotationUtils.getAnnotation(anns[i], Context.class) != null) {
       Object contextValue = contextValues != null ? contextValues.get(params[i]) : null;
       if (contextValue == null) {
         if (perRequest) {
           values[i] = JAXRSUtils.createContextValue(m, genericTypes[i], params[i]);
         } else {
           values[i] = InjectionUtils.createThreadLocalProxy(params[i]);
         }
       } else {
         values[i] = contextValue;
       }
     } else {
       // this branch won't execute for singletons given that the found constructor
       // is guaranteed to have only Context parameters, if any, for singletons
       Parameter p = ResourceUtils.getParameter(i, anns[i], params[i]);
       values[i] =
           JAXRSUtils.createHttpParameterValue(
               p, params[i], genericTypes[i], anns[i], m, templateValues, null);
     }
   }
   return values;
 }
예제 #21
0
  public static Constructor<?> findResourceConstructor(Class<?> resourceClass, boolean perRequest) {
    List<Constructor<?>> cs = new LinkedList<Constructor<?>>();
    for (Constructor<?> c : resourceClass.getConstructors()) {
      Class<?>[] params = c.getParameterTypes();
      Annotation[][] anns = c.getParameterAnnotations();
      boolean match = true;
      for (int i = 0; i < params.length; i++) {
        if (!perRequest) {
          if (AnnotationUtils.getAnnotation(anns[i], Context.class) == null) {
            match = false;
            break;
          }
        } else if (!AnnotationUtils.isValidParamAnnotations(anns[i])) {
          match = false;
          break;
        }
      }
      if (match) {
        cs.add(c);
      }
    }
    Collections.sort(
        cs,
        new Comparator<Constructor<?>>() {

          public int compare(Constructor<?> c1, Constructor<?> c2) {
            int p1 = c1.getParameterTypes().length;
            int p2 = c2.getParameterTypes().length;
            return p1 > p2 ? -1 : p1 < p2 ? 1 : 0;
          }
        });
    return cs.size() == 0 ? null : cs.get(0);
  }
예제 #22
0
  @SuppressWarnings("unchecked")
  private <T> T _get(Class<T> type, Set<Class<?>> seenTypes) {
    if (!seenTypes.add(type)) {
      throw new IllegalStateException("Cycle in dependencies for " + type);
    }

    Object singleton = singletons.get(type);
    if (singleton != null) {
      return (T) singleton;
    }

    try {
      Constructor<T> constructor = getConstructor(type);
      Class<?>[] parameterTypes = constructor.getParameterTypes();
      Object[] parameters = new Object[parameterTypes.length];
      for (int i = 0; i < parameterTypes.length; i++) {
        parameters[i] = _get(parameterTypes[i], seenTypes);
      }

      T instance = postProcess(constructor.newInstance(parameters));
      singletons.put(type, instance);
      return instance;
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
      throw new IllegalStateException("Unable to create instance of " + type);
    }
  }
예제 #23
0
파일: NewMethod.java 프로젝트: mindis/nuxeo
  public Object exec(List arguments) throws TemplateModelException {
    int size = arguments.size();
    if (size < 1) {
      throw new TemplateModelException("Invalid number of arguments for new(class, ...) method");
    }

    Class<?> klass;
    try {
      String className = (String) arguments.get(0);
      klass = Class.forName(className);
      if (size == 1) {
        return klass.newInstance();
      }
    } catch (ReflectiveOperationException e) {
      throw new TemplateModelException("Failed to isntantiate the object", e);
    }
    arguments.remove(0);
    Object[] ar = arguments.toArray();
    size--;
    Constructor<?>[] ctors = klass.getConstructors();
    for (Constructor<?> ctor : ctors) {
      Class<?>[] params = ctor.getParameterTypes(); // this is cloning params
      if (params.length == size) { // try this one
        try {
          return ctor.newInstance(ar);
        } catch (ReflectiveOperationException e) {
          // continue
        }
      }
    }
    throw new TemplateModelException("No suitable constructor found");
  }
예제 #24
0
  public static void register(Class<? extends Event> pore) {
    checkNotNull(pore, "pore");

    Class<? extends org.spongepowered.api.event.Event> sponge = null;
    for (Constructor<?> constructor : pore.getConstructors()) {
      Class<?>[] parameters = constructor.getParameterTypes();
      if (parameters.length == 1) {
        Class<?> parameter = parameters[0];
        if (org.spongepowered.api.event.Event.class.isAssignableFrom(parameter)) {
          sponge = parameter.asSubclass(org.spongepowered.api.event.Event.class);
        }
      }
    }

    checkArgument(sponge != null, "No event constructor found in %s", pore);

    Class<?> superClass = pore.getSuperclass();
    checkState(
        !Modifier.isAbstract(superClass.getModifiers())
            && superClass.getName().startsWith("org.bukkit.event"),
        "Not a Bukkit handle event %s",
        superClass);
    Class<? extends Event> handle = superClass.asSubclass(Event.class);

    HandlerList list = SimplePluginManager.getEventListeners(handle);
    list.addAdapter(create(pore, sponge));
  }
 public static void main(String[] args) throws Exception {
   Class clazz = Class.forName("com.mtl.spring.aop.helloworld.ArithmeticCalculatorLoggingProxy");
   Object object = clazz.newInstance();
   Method[] methods = clazz.getMethods();
   StringBuffer sb = new StringBuffer();
   sb.append("public class ")
       .append(object.getClass().getCanonicalName())
       .append("{\n")
       .append("Object object ")
       .append("\n");
   Constructor[] constructors = clazz.getConstructors();
   for (Constructor constructor : constructors) {
     sb.append("\npublic ").append(constructor.getName()).append("(");
     Class<?> p[] = constructor.getParameterTypes();
     for (int j = 0; j < p.length; ++j) {
       sb.append(p[j].getName() + " arg" + j);
       if (j < p.length - 1) {
         sb.delete(sb.length() - 1, sb.length());
       }
     }
     sb.append(") {").append("\n\n");
     sb.append("user.role.cotain(\"/admin/add\") {");
     sb.append("\n System.currentTimeMillis();\n");
     sb.append("this.object  = ").append("arg0");
     sb.append("}");
     sb.append(" \nSystem.currentTimeMillis();\n");
     sb.append("\n}");
   }
   sb.append("\n\n}");
   System.out.println(sb);
   for (Method method : methods) {
     System.out.println(method.getName());
   }
 }
예제 #26
0
  /**
   * Finds constructors of the specified access level in the supplied class.
   *
   * @param c the class to search in
   * @param level the access level to look for
   * @param sb the StringBuffer where the results should be added
   */
  private static void listConstructors(Class c, int level, StringBuffer sb) {
    Constructor[] constrs = c.getDeclaredConstructors();
    Constructor constructor;
    Class[] exceptions;
    StringBuffer cons;

    for (int index = 0; index < constrs.length; index++) {
      constructor = constrs[index];
      if (isAccessible(constructor.getModifiers(), level)) {
        cons = new StringBuffer(100);
        cons.append(printConstructor(constructor.getName(), constructor.getParameterTypes()));
        // Add exceptions
        exceptions = constructor.getExceptionTypes();

        if (exceptions.length > 0) {
          cons.append(printExceptions(exceptions));
        } else {
          cons.append(NIL);
        }
        cons.append(END_PAREN);
        if (sb.toString().lastIndexOf(cons.toString()) == -1) {
          sb.append(cons);
        }
      }
    }
  }
예제 #27
0
 // create a new random tokenizer from classpath
 private TokenizerSpec newTokenizer(Random random, Reader reader) {
   TokenizerSpec spec = new TokenizerSpec();
   while (spec.tokenizer == null) {
     final Constructor<? extends Tokenizer> ctor =
         tokenizers.get(random.nextInt(tokenizers.size()));
     final StringBuilder descr = new StringBuilder();
     final CheckThatYouDidntReadAnythingReaderWrapper wrapper =
         new CheckThatYouDidntReadAnythingReaderWrapper(reader);
     final Object args[] = newTokenizerArgs(random, wrapper, ctor.getParameterTypes());
     if (broken(ctor, args)) {
       continue;
     }
     spec.tokenizer = createComponent(ctor, args, descr);
     if (spec.tokenizer != null) {
       spec.offsetsAreCorrect &= !brokenOffsets(ctor, args);
       spec.toString = descr.toString();
     } else {
       assertFalse(
           ctor.getDeclaringClass().getName()
               + " has read something in ctor but failed with UOE/IAE",
           wrapper.readSomething);
     }
   }
   return spec;
 }
예제 #28
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;
          }
      }
    }
  }
예제 #29
0
 /** Creates a new instance of the specified type. */
 protected Object newInstance(Class<?> type) throws Exception {
   // find the most specific constructor that can take the last value
   if (_lvalue != null) {
     boolean inner = ReflectionUtil.isInner(type);
     _lvalue.getClass();
     Constructor cctor = null;
     Class<?> cptype = null;
     for (Constructor ctor : type.getConstructors()) {
       Class<?>[] ptypes = ctor.getParameterTypes();
       if (inner ? (ptypes.length != 2 || !ptypes[0].isInstance(_outer)) : (ptypes.length != 1)) {
         continue;
       }
       Class<?> ptype = ptypes[ptypes.length - 1];
       if (ptype.isInstance(_lvalue) && (cctor == null || cptype.isAssignableFrom(ptype))) {
         cctor = ctor;
         cptype = ptype;
       }
     }
     if (cctor != null) {
       return inner ? cctor.newInstance(_outer, _lvalue) : cctor.newInstance(_lvalue);
     }
   }
   // fall back on default constructor
   return ReflectionUtil.newInstance(type, _outer);
 }
예제 #30
0
 private static <T> T getInstanceFromNonDefaultConstructor(Class<T> targetClass) {
   Constructor<?>[] constructors = targetClass.getDeclaredConstructors();
   constructors = DatabaseFileLookupTest.orderByParamCount(constructors);
   for (Constructor<?> constructor : constructors) {
     constructor.setAccessible(true);
     Class<?>[] parameterTypes = constructor.getParameterTypes();
     try {
       /** Trying to invoke constructor with <code>null</code> values. */
       @SuppressWarnings("unchecked")
       T instance = (T) constructor.newInstance(new Object[parameterTypes.length]);
       return instance;
     } catch (Exception ignored) {
     }
     /** Creating proper instances for the parameter types. */
     Object[] arguments = DatabaseFileLookupTest.createArguments(parameterTypes, targetClass);
     if (arguments == null) {
       continue;
     }
     try {
       @SuppressWarnings("unchecked")
       T instance = (T) constructor.newInstance(arguments);
       return instance;
     } catch (Exception ignored) {
     }
   }
   return null;
 }