public void initTransactionManager(Environment env) {
    Object tm = env.get(EnvironmentName.TRANSACTION_MANAGER);
    if (env.get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER) != null
        && env.get(EnvironmentName.TRANSACTION_MANAGER) != null) {
      this.txm = (TransactionManager) tm;
      this.jpm = (PersistenceContextManager) env.get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
    } else {
      if (tm != null && tm.getClass().getName().startsWith("org.springframework")) {
        try {
          Class<?> cls =
              Class.forName(
                  "org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager");
          Constructor<?> con = cls.getConstructors()[0];
          this.txm = (TransactionManager) con.newInstance(tm);
          logger.debug("Instantiating  DroolsSpringTransactionManager");

          //                    if ( tm.getClass().getName().toLowerCase().contains( "jpa" ) ) {
          // configure spring for JPA and local transactions
          cls =
              Class.forName("org.drools.container.spring.beans.persistence.DroolsSpringJpaManager");
          con = cls.getConstructors()[0];
          this.jpm = (PersistenceContextManager) con.newInstance(new Object[] {this.env});
          //                    } else {
          //                        // configure spring for JPA and distributed transactions
          //                    }
        } catch (Exception e) {
          logger.warn("Could not instatiate DroolsSpringTransactionManager");
          throw new RuntimeException(
              "Could not instatiate org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager",
              e);
        }
      } else {
        logger.debug("Instantiating  JtaTransactionManager");
        this.txm =
            new JtaTransactionManager(
                env.get(EnvironmentName.TRANSACTION),
                env.get(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY),
                tm);
        try {
          Class<?> jpaPersistenceCtxMngrClass =
              Class.forName("org.jbpm.persistence.JpaProcessPersistenceContextManager");
          Constructor<?> jpaPersistenceCtxMngrCtor =
              jpaPersistenceCtxMngrClass.getConstructors()[0];
          this.jpm =
              (PersistenceContextManager)
                  jpaPersistenceCtxMngrCtor.newInstance(new Object[] {this.env});
        } catch (ClassNotFoundException e) {
          this.jpm = new JpaPersistenceContextManager(this.env);
        } catch (Exception e) {
          throw new RuntimeException("Error creating JpaProcessPersistenceContextManager", e);
        }
      }
      env.set(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, this.jpm);
      env.set(EnvironmentName.TRANSACTION_MANAGER, this.txm);
    }
  }
Example #2
1
    public void generateObjects(String arrayName, Object... parent) {
      if (mRec == null) return;

      Object rawObj;
      try {
        rawObj = mParser.parse(mJson);
        if (rawObj == null) return;

        JSONObject obj = (JSONObject) rawObj;
        JSONArray arr = (JSONArray) obj.get(arrayName);
        int cnt = 0;
        if (arr != null) {
          for (Object jb : arr.toArray()) // each object
          {
            JSONObject jo = (JSONObject) jb;
            mCls.getConstructors()[0].setAccessible(true);

            Object w;
            if (parent != null && parent.length != 0) // Inner class
            w = mCls.getConstructors()[0].newInstance(parent[0]);
            else {
              w = mCls.getConstructors()[0].newInstance((Object) null);
            }
            for (Field f : mCls.getDeclaredFields()) // each field
            {
              try {
                Object fieldVal = jo.get(f.getName());
                if (fieldVal == null) continue;
                if (f.getType() == Integer.class) f.set(w, Integer.parseInt(fieldVal.toString()));
                else if (f.getType() == Date.class)
                  f.set(w, new Date(Long.parseLong(fieldVal.toString())));
                else if (f.getType() == String.class) f.set(w, fieldVal.toString());
              } catch (IllegalArgumentException e) {
                e.printStackTrace();
              } catch (IllegalAccessException e) {
                e.printStackTrace();
              }
            }
            mRec.receiveObject(w);
          }
        }
      } catch (ParseException e1) {
        e1.printStackTrace();
      } catch (IllegalArgumentException e1) {
        e1.printStackTrace();
      } catch (SecurityException e1) {
        e1.printStackTrace();
      } catch (InstantiationException e1) {
        e1.printStackTrace();
      } catch (IllegalAccessException e1) {
        e1.printStackTrace();
      } catch (InvocationTargetException e1) {
        e1.printStackTrace();
      }
    }
Example #3
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
            + "\"");
  }
 // ------ Common stuff
 static Model createModel(
     String simClass, String _ownerName, java.awt.Frame _ownerFrame, java.net.URL _codebase) {
   Model aModel = null;
   if (_ownerName != null || _codebase != null) {
     try { // Instantiate a model with the given name and three parameters
       Class c = Class.forName(simClass);
       Constructor[] constructors = c.getConstructors();
       for (int i = 0; i < constructors.length; i++) {
         Class[] parameters = constructors[i].getParameterTypes();
         if (parameters.length == 3
             && parameters[0].isAssignableFrom(_ownerName.getClass())
             && parameters[1].isAssignableFrom(_ownerFrame.getClass())
             && parameters[2].isAssignableFrom(_codebase.getClass())) {
           aModel =
               (Model)
                   constructors[i].newInstance(new Object[] {_ownerName, _ownerFrame, _codebase});
           break;
         }
       }
     } catch (Exception exc) {
       exc.printStackTrace();
       aModel = null;
     }
   }
   if (aModel == null) {
     try { // Now try a simple constructor
       Class aClass = Class.forName(simClass);
       aModel = (Model) aClass.newInstance();
     } catch (Exception exc) {
       exc.printStackTrace();
       return null;
     }
   }
   return aModel;
 }
Example #5
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);
 }
Example #6
1
  protected ArrayList createListCompletions(Package setOfCompletions) {
    ArrayList listOfCompletions = new ArrayList();

    for (Item i : setOfCompletions) {
      try {
        try {
          if (i instanceof ClassName) {
            String fullName = getFullName(setOfCompletions.getName(), ((ClassName) i).getName());
            Class clazz = getClass().getClassLoader().loadClass(fullName);
            Constructor[] ctor = clazz.getConstructors();

            for (Constructor c : ctor) {
              String cotrCompletion = createConstructorCompletion(c.toString());
              listOfCompletions.add(new BasicCompletion(defaultProvider, cotrCompletion));
            }
            listOfCompletions.add(new BasicCompletion(defaultProvider, i.getName() + "."));
          }
        } catch (NoClassDefFoundError e) {
          e.printStackTrace();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      listOfCompletions.add(new BasicCompletion(defaultProvider, i.getName()));
    }
    return listOfCompletions;
  }
  public CepQuery createCepQuery(final String command) {
    // TODO: Correct it, it should NEVER return null!
    Class<?> c = null;
    CepQuery e = null;

    try {
      c = Class.forName(this.cepQueryName);

      final Constructor<?>[] ctors = c.getConstructors();
      e = (CepQuery) ctors[0].newInstance(command);
      return e;

    } catch (final IllegalAccessException ex) {
      ex.printStackTrace();
      return null;
    } catch (final ClassNotFoundException ex) {
      ex.printStackTrace();
      return null;
    } catch (final InstantiationException ex) {
      ex.printStackTrace();
      return null;
    } catch (final IllegalArgumentException ex) {
      // TODO Auto-generated catch block
      ex.printStackTrace();
    } catch (final InvocationTargetException ex) {
      // TODO Auto-generated catch block
      ex.printStackTrace();
    }

    return null;
  }
 /**
  * Instantiates a new Standalone
  *
  * @param classLoader the ClassLoader used to instantiate class
  * @param args the arguments passed to Standalone
  * @throws ClassNotFoundException
  * @throws InstantiationException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  */
 private void newStandalone(URLClassLoader classLoader, String[] args)
     throws ClassNotFoundException, InstantiationException, IllegalAccessException,
         InvocationTargetException {
   Class nanoStandalone = classLoader.loadClass("org.nanocontainer.Standalone");
   Constructor constructor = nanoStandalone.getConstructors()[0];
   constructor.newInstance(args);
 }
  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;
  }
Example #10
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);
 }
 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());
   }
 }
  /**
   * @todo pico components can have theoretically more then one constructor which is rather stupid
   *     idea
   */
  public Object newInstance(
      ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container)
      throws ComponentInstantiationException {
    try {

      String implementation = componentDescriptor.getImplementation();

      Class implementationClass = classRealm.loadClass(implementation);

      Constructor constructor = implementationClass.getConstructors()[0];

      Class[] parameterTypes = constructor.getParameterTypes();

      Object[] params = new Object[parameterTypes.length];

      for (int i = 0; i < parameterTypes.length; i++) {
        Class parameterType = parameterTypes[i];

        params[i] = lookupComponent(parameterType, componentDescriptor, container);
      }

      Object retValue = constructor.newInstance(params);

      return retValue;

    } catch (Exception e) {
      String msg =
          "Component " + componentDescriptor.getHumanReadableKey() + " cannot be instantiated";

      throw new ComponentInstantiationException(msg, e);
    }
  }
 /**
  * 反射取得ViewItemHelper的实例
  *
  * <p>这里在反射构造的时候,如果BaseViewHolder是static class 则不需要mConstructObject实例作为构造参数
  * 所要创建BaseViewHolder类必须存在public的构造
  * 如果是Activity或者fragment的内部类,则需要activity或者fragm的实例作为第一个参数,这里mConstructContext就是activity
  *
  * @param cls BaseViewHolder的class
  * @param mItemView
  * @param mConstructObject BaseViewHolder 实例的构造参数,如果BaseViewHolder是activity或者fragment的内部类,
  *     该参数就是activity或者fragment的对象
  * @return 一个BaseViewHolder实例
  */
 public static BaseViewHolder createViewItemInstance(
     Class cls, View mItemView, Object mConstructObject) {
   try {
     Constructor<BaseViewHolder>[] constructors = cls.getConstructors();
     if (constructors == null && constructors.length == 0) {
       return null;
     }
     for (Constructor<BaseViewHolder> mCons : constructors) {
       Class[] mParameterTypes = mCons.getParameterTypes();
       Object[] params = null;
       switch (mParameterTypes.length) {
         case 1:
           params = new Object[] {mItemView};
           return mCons.newInstance(params);
         case 2:
           params = new Object[] {mConstructObject, mItemView};
           return mCons.newInstance(params);
       }
     }
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   }
   return null;
 }
  @SuppressWarnings("unchecked")
  public void readData(SpoutInputStream input) throws IOException {
    String packetName = input.readString();

    boolean sandboxed = SpoutClient.isSandboxed();
    SpoutClient.enableSandbox();

    try {
      Class<? extends AddonPacket> packetClass = AddonPacket.getPacketFromId(packetName);
      Constructor<? extends AddonPacket> constructor = null;
      Constructor<? extends AddonPacket>[] constructors =
          (Constructor<? extends AddonPacket>[]) packetClass.getConstructors();
      for (Constructor<? extends AddonPacket> c : constructors) {
        if (c.getGenericParameterTypes().length == 0) {
          constructor = c;
          break;
        }
      }
      packet = constructor.newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (!sandboxed) {
      SpoutClient.disableSandbox();
    }

    int size = input.readInt();
    compressed = input.readBoolean();
    data = new byte[size];
    input.read(data);
  }
 /**
  * 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;
 }
Example #16
0
 @SuppressWarnings("unchecked")
 private static <T> T instantiate(
     Class<T> clazz, List<Class<?>> matchingClasses, Object... preInstancedDependencies) {
   try {
     logger.info("Creating instance of: " + clazz);
     Constructor<?> clazzConstructor = Stream.of(clazz.getConstructors()).findFirst().get();
     Class<?>[] parameterTypes = clazzConstructor.getParameterTypes();
     if (parameterTypes.length > 0) {
       Object[] paramInstances =
           Stream.of(parameterTypes)
               .map(
                   paramType ->
                       Stream.of(preInstancedDependencies)
                           .filter(obj -> paramType.isInstance(obj))
                           .findFirst()
                           .orElseGet(
                               () ->
                                   instantiate(
                                       paramType, matchingClasses, preInstancedDependencies)))
               .toArray();
       return (T) clazzConstructor.newInstance(paramInstances);
     } else {
       return clazz.newInstance();
     }
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 public static void main(String[] args) {
   if (args.length < 1) {
     print(usage);
     System.exit(0);
   }
   int lines = 0;
   try {
     Class<?> c = Class.forName(args[0]);
     Method[] methods = c.getMethods();
     Constructor[] ctors = c.getConstructors();
     if (args.length == 1) {
       for (Method method : methods) print(p.matcher(method.toString()).replaceAll(""));
       for (Constructor ctor : ctors) print(p.matcher(ctor.toString()).replaceAll(""));
       lines = methods.length + ctors.length;
     } else {
       for (Method method : methods)
         if (method.toString().indexOf(args[1]) != -1) {
           print(p.matcher(method.toString()).replaceAll(""));
           lines++;
         }
       for (Constructor ctor : ctors)
         if (ctor.toString().indexOf(args[1]) != -1) {
           print(p.matcher(ctor.toString()).replaceAll(""));
           lines++;
         }
     }
   } catch (ClassNotFoundException e) {
     print("No such class: " + e);
   }
 }
Example #18
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;
 }
  @Nullable
  private static String getNamedAnnotationValue(
      final Class<?> injectClass, final Class<?> intoClass) {

    for (final Constructor<?> constructor : intoClass.getConstructors()) {

      if (!constructor.isAnnotationPresent(Inject.class)) {
        continue;
      }

      final Annotation[][] paramAnnotations = constructor.getParameterAnnotations();

      final Class<?>[] paramTypes = constructor.getParameterTypes();

      for (int i = 0; i < paramTypes.length; ++i) {

        if (!injectClass.equals(paramTypes[i])) {
          continue;
        }

        for (int j = 0; j < paramAnnotations[i].length; ++j) {

          final Annotation paramAnnotation = paramAnnotations[i][j];

          if (Named.class.equals(paramAnnotation.annotationType())) {

            return ((Named) paramAnnotation).value();
          }
        }
      }
    }

    return null;
  }
 static {
   try {
     for (Class<?> c :
         Arrays.<Class<?>>asList(
             ReversePathHierarchyTokenizer.class,
             PathHierarchyTokenizer.class,
             // TODO: it seems to mess up offsets!?
             WikipediaTokenizer.class,
             // TODO: doesn't handle graph inputs
             CJKBigramFilter.class,
             // TODO: doesn't handle graph inputs (or even look at positionIncrement)
             HyphenatedWordsFilter.class,
             // TODO: LUCENE-4983
             CommonGramsFilter.class,
             // TODO: doesn't handle graph inputs
             CommonGramsQueryFilter.class,
             // TODO: probably doesnt handle graph inputs, too afraid to try
             WordDelimiterFilter.class)) {
       for (Constructor<?> ctor : c.getConstructors()) {
         brokenOffsetsConstructors.put(ctor, ALWAYS);
       }
     }
   } catch (Exception e) {
     throw new Error(e);
   }
 }
  /** Creates a service and its associated manager based on fully qualified class names. */
  private Service setupService(String serviceName, String managerName, HashSet<Object> managerSet)
      throws Exception {
    // get the service class and instance
    Class<?> serviceClass = Class.forName(serviceName);
    Service service = createService(serviceClass);

    // resolve the class and the constructor, checking for constructors
    // by type since they likely take a super-type of Service
    Class<?> managerClass = Class.forName(managerName);
    Constructor<?>[] constructors = managerClass.getConstructors();
    Constructor<?> managerConstructor = null;
    for (int i = 0; i < constructors.length; i++) {
      Class<?>[] types = constructors[i].getParameterTypes();
      if (types.length == 1) {
        if (types[0].isAssignableFrom(serviceClass)) {
          managerConstructor = constructors[i];
          break;
        }
      }
    }

    // if we didn't find a matching manager constructor, it's an error
    if (managerConstructor == null)
      throw new NoSuchMethodException(
          "Could not find a constructor " + "that accepted the Service");

    // create the manager and put it in the collection
    managerSet.add(managerConstructor.newInstance(service));

    return service;
  }
Example #22
0
 private void setWriter(ValueVector v) {
   state = State.SINGLE;
   vector = v;
   type = v.getField().getType().getMinorType();
   Class<?> writerClass =
       BasicTypeHelper.getWriterImpl(
           v.getField().getType().getMinorType(), v.getField().getDataMode());
   if (writerClass.equals(SingleListWriter.class)) {
     writerClass = UnionListWriter.class;
   }
   Class<? extends ValueVector> vectorClass =
       BasicTypeHelper.getValueVectorClass(
           v.getField().getType().getMinorType(), v.getField().getDataMode());
   try {
     Constructor<?> constructor = null;
     for (Constructor<?> c : writerClass.getConstructors()) {
       if (c.getParameterTypes().length == 3) {
         constructor = c;
       }
     }
     if (constructor == null) {
       constructor = writerClass.getConstructor(vectorClass, AbstractFieldWriter.class);
       writer = (FieldWriter) constructor.newInstance(vector, null);
     } else {
       writer = (FieldWriter) constructor.newInstance(vector, null, true);
     }
   } catch (ReflectiveOperationException e) {
     throw new RuntimeException(e);
   }
 }
Example #23
0
 /**
  * ****************************************************************************
  * 反射方法,打印对象的属性,方法,构造器属性
  *
  * @param obj 被反射对象 ***************************************************************************
  */
 public static void reflect(Object obj) {
   Class<?> cls = obj.getClass();
   System.out.println("************构  造  器************");
   Constructor<?>[] constructors = cls.getConstructors();
   for (Constructor<?> constructor : constructors) {
     System.out.println(
         "构造器名称:"
             + constructor.getName()
             + "\t"
             + "    "
             + "构造器参数类型:"
             + Arrays.toString(constructor.getParameterTypes()));
   }
   System.out.println("************属     性************");
   Field[] fields = cls.getDeclaredFields();
   // cls.getFields() 该方法只能访问共有的属性
   // cls.getDeclaredFields()  可以访问私有属性
   for (Field field : fields) {
     System.out.println("属性名称:" + field.getName() + "\t" + "属性类型:" + field.getType() + "\t");
   }
   System.out.println("************方   法************");
   Method[] methods = cls.getMethods();
   for (Method method : methods) {
     System.out.println(
         "方法名:"
             + method.getName()
             + "\t"
             + "方法返回类型:"
             + method.getReturnType()
             + "\t"
             + "方法参数类型:"
             + Arrays.toString(method.getParameterTypes()));
   }
 }
 @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());
 }
Example #25
0
  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    Class clazz = Class.forName("com.jsonwang.reflection.clazz.User");
    System.out.println(clazz.getName());
    System.out.println(clazz.getSimpleName());
    // Field[] fields = clazz.getFields(); //for public fields
    Field[] fields = clazz.getDeclaredFields();
    for (Field f : fields) {
      System.out.println(f.getName());
    }
    Method[] methods =
        clazz
            .getDeclaredMethods(); // getMethods() this method can get All methods include notifyAll
                                   // etc.
    for (Method m : methods) {
      System.out.println(m.getName());
    }
    System.out.println("getName   :  " + clazz.getMethod("getName", null));
    System.out.println("setName   :  " + clazz.getMethod("setName", String.class));

    Constructor[] constructors = clazz.getConstructors();
    Constructor c = clazz.getDeclaredConstructor(String.class, int.class);
    System.out.println(c);
    for (Constructor constructor : constructors) {
      System.out.println("constructor  :  " + constructor);
    }
  }
Example #26
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);
  }
Example #27
0
  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");
  }
Example #28
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));
  }
  /**
   * Returns a vector with all constructors named <code>_fname</code> after stripping its namespace
   * or <code>null</code> if no such methods exist.
   */
  private Vector findConstructors() {
    Vector result = null;
    final String namespace = _fname.getNamespace();

    final int nArgs = _arguments.size();
    try {
      if (_clazz == null) {
        _clazz = ObjectFactory.findProviderClass(_className, ObjectFactory.findClassLoader(), true);

        if (_clazz == null) {
          final ErrorMsg msg = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className);
          getParser().reportError(Constants.ERROR, msg);
        }
      }

      final Constructor[] constructors = _clazz.getConstructors();

      for (int i = 0; i < constructors.length; i++) {
        final int mods = constructors[i].getModifiers();
        // Is it public, static and same number of args ?
        if (Modifier.isPublic(mods) && constructors[i].getParameterTypes().length == nArgs) {
          if (result == null) {
            result = new Vector();
          }
          result.addElement(constructors[i]);
        }
      }
    } catch (ClassNotFoundException e) {
      final ErrorMsg msg = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className);
      getParser().reportError(Constants.ERROR, msg);
    }

    return result;
  }
Example #30
0
 static {
   try {
     brokenConstructors.put(
         LimitTokenCountFilter.class.getConstructor(TokenStream.class, int.class), ALWAYS);
     brokenConstructors.put(
         LimitTokenCountFilter.class.getConstructor(TokenStream.class, int.class, boolean.class),
         new Predicate<Object[]>() {
           @Override
           public boolean apply(Object[] args) {
             assert args.length == 3;
             return !((Boolean) args[2]); // args are broken if consumeAllTokens is false
           }
         });
     brokenConstructors.put(
         LimitTokenPositionFilter.class.getConstructor(TokenStream.class, int.class), ALWAYS);
     brokenConstructors.put(
         LimitTokenPositionFilter.class.getConstructor(
             TokenStream.class, int.class, boolean.class),
         new Predicate<Object[]>() {
           @Override
           public boolean apply(Object[] args) {
             assert args.length == 3;
             return !((Boolean) args[2]); // args are broken if consumeAllTokens is false
           }
         });
     for (Class<?> c :
         Arrays.<Class<?>>asList(
             // TODO: can we promote some of these to be only
             // offsets offenders?
             // doesn't actual reset itself!
             CachingTokenFilter.class,
             // Not broken: we forcefully add this, so we shouldn't
             // also randomly pick it:
             ValidatingTokenFilter.class,
             // NOTE: these by themselves won't cause any 'basic assertions' to fail.
             // but see https://issues.apache.org/jira/browse/LUCENE-3920, if any
             // tokenfilter that combines words (e.g. shingles) comes after them,
             // this will create bogus offsets because their 'offsets go backwards',
             // causing shingle or whatever to make a single token with a
             // startOffset thats > its endOffset
             // (see LUCENE-3738 for a list of other offenders here)
             // broken!
             NGramTokenizer.class,
             // broken!
             NGramTokenFilter.class,
             // broken!
             EdgeNGramTokenizer.class,
             // broken!
             EdgeNGramTokenFilter.class,
             // broken!
             WordDelimiterFilter.class)) {
       for (Constructor<?> ctor : c.getConstructors()) {
         brokenConstructors.put(ctor, ALWAYS);
       }
     }
   } catch (Exception e) {
     throw new Error(e);
   }
 }