コード例 #1
0
ファイル: ReflectionUtil.java プロジェクト: luowei/demo-repo
  /**
   * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
   *
   * <p>如public UserDao extends HibernateDao<User,Long>
   *
   * @param clazz clazz The class to introspect
   * @param index the Index of the generic ddeclaration,start from 0.
   * @return the index generic declaration, or Object.class if cannot be determined
   */
  public static Class getSuperClassGenricType(final Class clazz, final int index) {

    Type genType = clazz.getGenericSuperclass();

    if (!(genType instanceof ParameterizedType)) {
      logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
      return Object.class;
    }

    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

    if (index >= params.length || index < 0) {
      logger.warn(
          "Index: "
              + index
              + ", Size of "
              + clazz.getSimpleName()
              + "'s Parameterized Type: "
              + params.length);
      return Object.class;
    }
    if (!(params[index] instanceof Class)) {
      logger.warn(
          clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
      return Object.class;
    }

    return (Class) params[index];
  }
コード例 #2
0
 public void mapToType(Class<?> type) {
   if (!targetType.isAssignableFrom(type)) {
     throw new IllegalArgumentException(
         String.format(
             "requested wrapper type '%s' is not assignable to target type '%s'.",
             type.getSimpleName(), targetType.getSimpleName()));
   }
   wrapperType = type;
 }
コード例 #3
0
ファイル: WireByMethod.java プロジェクト: JEC2000/Projet_ARA
  /**
   * Search a wiring method in the specified class.
   *
   * @param cl the class where to find the method
   * @param methodName the method to be searched
   * @return the requested method, if it fully conforms to the definition of the wiring methods.
   */
  private static Method getMethod(Class cl, String methodName)
      throws NoSuchMethodException, ClassNotFoundException {

    // Search methods
    Method[] methods = cl.getMethods();
    ArrayList<Method> list = new ArrayList<Method>();
    for (Method m : methods) {
      if (m.getName().equals(methodName)) {
        list.add(m);
      }
    }

    if (list.size() == 0) {
      throw new NoSuchMethodException(
          "No method " + methodName + " in class " + cl.getSimpleName());
    } else if (list.size() > 1) {
      throw new NoSuchMethodException(
          "Multiple methods called " + methodName + " in class " + cl.getSimpleName());
    }

    // Found a single method with the right name; check if
    // it is a setter.
    final Class graphClass = Class.forName("peersim.graph.Graph");
    final Class randomClass = Class.forName("java.util.Random");
    Method method = list.get(0);
    Class[] pars = method.getParameterTypes();
    if (pars.length < 1 || !pars[0].isAssignableFrom(graphClass))
      throw new NoSuchMethodException(
          method.getName()
              + " of class "
              + cl.getSimpleName()
              + " is not a valid graph wiring method,"
              + " it has to have peersim.graph.Graph as first argument type");
    for (int i = 1; i < pars.length; ++i)
      if (!(pars[i] == int.class
          || pars[i] == long.class
          || pars[i] == double.class
          || (i == pars.length - 1 && pars[i].isAssignableFrom(randomClass))))
        throw new NoSuchMethodException(
            method.getName()
                + " of class "
                + cl.getSimpleName()
                + " is not a valid graph wiring method");

    if (method.toString().indexOf("static") < 0)
      throw new NoSuchMethodException(
          method.getName()
              + " of class "
              + cl.getSimpleName()
              + " is not a valid graph wiring method; it is not static");

    return method;
  }
コード例 #4
0
 private static int checkSingleArgument(
     String subroutineName,
     Class expectedType,
     ArgumentsList arguments,
     List<LispObject> args,
     int argsCounter,
     int i) {
   try {
     if (!(expectedType.isInstance(args.get(argsCounter)))) {
       if (expectedType.equals(LispList.class)
           && args.get(argsCounter).equals(LispSymbol.ourNil)) {
         arguments.setValue(i, LispList.list());
         return argsCounter + 1;
       }
       if (expectedType.equals(LispSymbol.class)
           && args.get(argsCounter).equals(LispSymbol.ourNil)) {
         arguments.setValue(i, LispSymbol.ourNil);
         return argsCounter + 1;
       }
       if (arguments.isOptional(i)) return -1;
       throw new WrongTypeArgumentException(expectedType.getSimpleName(), args.get(argsCounter));
     }
     arguments.setValue(i, args.get(argsCounter));
     return argsCounter + 1;
   } catch (IndexOutOfBoundsException e) {
     if (arguments.isOptional(i)) return -1;
     throw new WrongNumberOfArgumentsException(subroutineName, i);
   }
 }
コード例 #5
0
 public String toString() {
   return "type="
       + type.getSimpleName()
       + ",data="
       + data.getClass().getSimpleName()
       + ':'
       + data;
 }
コード例 #6
0
 @Override
 public String toString() {
   StringBuilder b = new StringBuilder();
   for (Class<?> ann : annotations) {
     b.append(ann.getSimpleName()).append(' ');
   }
   b.append((type instanceof Class<?>) ? ((Class<?>) type).getSimpleName() : type.toString());
   return b.toString();
 }
コード例 #7
0
ファイル: BaseMod.java プロジェクト: nevercast/SGCraft
 public void registerEntity(
     Class<? extends Entity> cls,
     String name,
     int id,
     int updateFrequency,
     boolean sendVelocityUpdates) {
   System.out.printf(
       "%s: BaseMod.registerEntity: %s, \"%s\", %s\n",
       getClass().getSimpleName(), cls.getSimpleName(), name, id);
   EntityRegistry.registerModEntity(
       cls, name, id, /*base*/ this, 256, updateFrequency, sendVelocityUpdates);
 }
コード例 #8
0
 public MethodCallTester<MonitoredClass> assertMethodNotCalled(
     String name, Class<?>... paramTypes) {
   assertFalse(
       "Method "
           + mockClass.getSimpleName()
           + "."
           + name
           + "("
           + Arrays.toString(paramTypes)
           + ") was called but no call was expected",
       wasMethodCalled(name, paramTypes));
   return this;
 }
コード例 #9
0
 public MethodCallTester<MonitoredClass> assertMethodCalled(
     String name, Object... expectedParamValues) {
   assertTrue(
       "Method "
           + mockClass.getSimpleName()
           + "."
           + name
           + "("
           + Arrays.toString(expectedParamValues)
           + ") was not called",
       wasMethodCalled(name, expectedParamValues));
   return this;
 }
コード例 #10
0
 @SuppressWarnings("unused")
 public MethodCallTester<MonitoredClass> assertMethodNotCalled(
     String name, Object... expectedParamValues) {
   assertFalse(
       "Method "
           + mockClass.getSimpleName()
           + "."
           + name
           + "("
           + Arrays.toString(expectedParamValues)
           + ") was called but no call was expected",
       wasMethodCalled(name, expectedParamValues));
   return this;
 }
コード例 #11
0
ファイル: BeanUtil.java プロジェクト: gmeurant/benerator
 /**
  * Creates an instance of the class using the default constructor.
  *
  * @since 0.2.06
  */
 @SuppressWarnings("cast")
 private static <T> T newInstanceFromDefaultConstructor(Class<T> type) {
   if (type == null) return null;
   if (logger.isDebugEnabled()) logger.debug("Instantiating " + type.getSimpleName());
   if (deprecated(type))
     escalator.escalate(
         "Instantiating a deprecated class: " + type.getName(), BeanUtil.class, null);
   try {
     return (T) type.newInstance();
   } catch (InstantiationException e) {
     throw ExceptionMapper.configurationException(e, type);
   } catch (IllegalAccessException e) {
     throw ExceptionMapper.configurationException(e, type);
   }
 }
コード例 #12
0
 @Override
 public void execute() {
   // to insert the selected string into the document
   int pos = editor.getTextPaneEditor().getCaretPosition() - 1;
   String content = null;
   try {
     content = editor.getTextPaneEditor().getText(0, pos + 1);
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
   int w;
   for (w = pos; w >= 0; w--) {
     if (!Character.isLetter(content.charAt(w))) {
       break;
     }
   }
   String prefix = content.substring(w + 1).toLowerCase();
   try {
     String toInsert = getName().substring(prefix.length(), getName().length());
     String[] args = null;
     for (Method m : GraphOEditor.class.getMethods()) {
       if (m.getName().equals(getName())) {
         if (!(m.getParameterTypes().length == 0)) {
           args = new String[m.getParameterTypes().length];
         }
         int cpt = 0;
         for (Class c : m.getParameterTypes()) {
           args[cpt] = c.getSimpleName();
           cpt = cpt + 1;
         }
       }
     }
     toInsert = toInsert + "(";
     if (!(args == null)) {
       for (int i = 0; i < args.length; i++) {
         if (i == (args.length - 1)) {
           toInsert = toInsert + args[i];
         } else {
           toInsert = toInsert + args[i] + ",";
         }
       }
     }
     toInsert = toInsert + ");";
     editor.getTextPaneEditor().getDocument().insertString(pos + 1, toInsert, null);
   } catch (BadLocationException e) {
     e.printStackTrace();
   }
 }
コード例 #13
0
    public boolean matchesDestructor(Class<?> type) {
      if (!symbol.contains(type.getSimpleName())) {
        return false;
      }

      parse();

      try {
        if (ref != null) {
          return ref.matchesDestructor(type);
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      return false;
    }
コード例 #14
0
    /**
     * Check that all methods declared in the given interface were called. Does *not* include
     * methods from super interfaces.
     *
     * @return this for fluent api
     */
    public MethodCallTester<MonitoredClass> assertAllInterfaceMethodsCalled() {
      List<MethodInvocation> currentInvocation =
          new ArrayList<>(invocations); // Debugger calling toString can mess with this
      for (Method method : mockClass.getDeclaredMethods()) {
        if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers()))
          continue;

        boolean called = false;
        for (MethodInvocation invocation : currentInvocation) {
          if (invocation.method.equals(method.getName())) {
            called = true;
            break;
          }
        }

        assertTrue(
            "Method " + mockClass.getSimpleName() + "." + method.getName() + " was not called",
            called);
      }
      return this;
    }
コード例 #15
0
 private static <T, S> T adaptToEnum(Class<T> targetType, S sourceObject) {
   try {
     String literal;
     if (sourceObject instanceof Enum) {
       literal = ((Enum<?>) sourceObject).name();
     } else if (sourceObject instanceof String) {
       literal = (String) sourceObject;
     } else {
       literal = sourceObject.toString();
     }
     NotationParser<String, T> parser =
         new NotationConverterToNotationParserAdapter<String, T>(
             new EnumFromCharSequenceNotationParser(targetType));
     T parsedLiteral = parser.parseNotation(literal);
     return targetType.cast(parsedLiteral);
   } catch (TypeConversionException e) {
     throw new IllegalArgumentException(
         String.format(
             "Can't convert '%s' to enum type '%s'", sourceObject, targetType.getSimpleName()),
         e);
   }
 }
コード例 #16
0
ファイル: BeanUtil.java プロジェクト: gmeurant/benerator
  public static String toString(Object bean, boolean simple) {
    if (bean == null) return null;
    Class<?> beanClass = bean.getClass();
    StringBuilder builder =
        new StringBuilder(simple ? beanClass.getSimpleName() : bean.getClass().getName());
    PropertyDescriptor[] descriptors = getPropertyDescriptors(bean.getClass());
    boolean first = true;
    for (PropertyDescriptor descriptor : descriptors) {
      String propertyName = descriptor.getName();
      if (!"class".equals(propertyName) && descriptor.getReadMethod() != null) {
        if (first) builder.append('[');
        else builder.append(", ");

        Object value = getPropertyValue(bean, propertyName);
        String valueString = ToStringConverter.convert(value, "null");
        builder.append(propertyName).append("=").append(valueString);
        first = false;
      }
    }
    if (!first) builder.append(']');
    return builder.toString();
  }
コード例 #17
0
 NullRobotProxyHandler(Class<? extends Robot> type) {
   nullName = type.getSimpleName() + " NullRobot";
 }
コード例 #18
0
 public String getPublicMethodsForClasses(String classNames[]) {
   StringBuilder result = new StringBuilder();
   String className = null;
   result.append("<classDefinitions>");
   if (classNames != null && classNames.length > 0) {
     for (int i = 0; i < classNames.length; i++) {
       className = classNames[i];
       if (className != null) {
         result.append("<classDefinition>");
         try {
           Class c = Class.forName(className);
           result.append(
               (new StringBuilder("<classSimpleName>"))
                   .append(c.getSimpleName())
                   .append("</classSimpleName>")
                   .toString());
           result.append(
               (new StringBuilder("<classFullName>"))
                   .append(c.getName())
                   .append("</classFullName>")
                   .toString());
           Package pack = c.getPackage();
           String packStr = "";
           if (pack != null) packStr = pack.getName();
           result.append(
               (new StringBuilder("<packageName>"))
                   .append(packStr)
                   .append("</packageName>")
                   .toString());
           Method methods[] = c.getMethods();
           Method method = null;
           result.append("<methods>");
           if (methods != null) {
             for (int j = 0; j < methods.length; j++) {
               method = methods[j];
               if (method != null && !methodsExclude.contains(method.getName())) {
                 result.append("<method>");
                 result.append(
                     (new StringBuilder("<methodSignature>"))
                         .append(method.toString())
                         .append("</methodSignature>")
                         .toString());
                 result.append(
                     (new StringBuilder("<methodName>"))
                         .append(method.getName())
                         .append("</methodName>")
                         .toString());
                 result.append(
                     (new StringBuilder("<returnType>"))
                         .append(method.getReturnType().getName())
                         .append("</returnType>")
                         .toString());
                 Class paramClasses[] = method.getParameterTypes();
                 result.append("<params>");
                 if (paramClasses != null) {
                   for (int l = 0; l < paramClasses.length; l++)
                     if (paramClasses[l] != null)
                       result.append(
                           (new StringBuilder("<param>"))
                               .append(paramClasses[l].getName())
                               .append("</param>")
                               .toString());
                 }
                 result.append("</params>");
                 result.append("</method>");
               }
             }
           }
           result.append("</methods>");
         } catch (ClassNotFoundException e) {
           result.append(
               (new StringBuilder("<classFullName>"))
                   .append(className)
                   .append("</classFullName>")
                   .toString());
           result.append(
               (new StringBuilder("<error>Problem retrieving "))
                   .append(className)
                   .append(" information</error>")
                   .toString());
           System.out.println(e.getMessage());
         }
         result.append("</classDefinition>");
       }
     }
   }
   result.append("</classDefinitions>");
   return result.toString();
 }
コード例 #19
0
  public String getPublicPropertiesForClasses(String classNames[]) {
    StringBuilder result = new StringBuilder();
    String className = null;
    ArrayList publicFields = new ArrayList();
    result.append("<classDefinitions>");
    if (classNames != null && classNames.length > 0) {
      for (int i = 0; i < classNames.length; i++) {
        className = classNames[i];
        if (className != null) {
          result.append("<classDefinition>");
          try {
            Class c = Class.forName(className);
            Field fields[] = c.getFields();
            Field field = null;
            if (fields != null) {
              for (int k = 0; k < fields.length; k++) {
                field = fields[k];
                if (field != null)
                  publicFields.add(
                      (new StringBuilder(String.valueOf(field.getName())))
                          .append(",")
                          .append(field.getType().getName())
                          .toString());
              }
            }
            try {
              BeanInfo b = Introspector.getBeanInfo(c);
              result.append(
                  (new StringBuilder("<classSimpleName>"))
                      .append(c.getSimpleName())
                      .append("</classSimpleName>")
                      .toString());
              result.append(
                  (new StringBuilder("<classFullName>"))
                      .append(c.getName())
                      .append("</classFullName>")
                      .toString());
              Package pack = c.getPackage();
              String packStr = "";
              if (pack != null) packStr = pack.getName();
              result.append(
                  (new StringBuilder("<packageName>"))
                      .append(packStr)
                      .append("</packageName>")
                      .toString());
              PropertyDescriptor pds[] = b.getPropertyDescriptors();
              if (pds != null) {
                for (int propCount = 0; propCount < pds.length; propCount++) {
                  PropertyDescriptor pd = pds[propCount];
                  String propertyName = pd.getName();
                  Method readMethod = pd.getReadMethod();
                  Method writeMethod = pd.getWriteMethod();
                  if (readMethod != null
                      && isPublicAccessor(readMethod.getModifiers())
                      && writeMethod != null
                      && isPublicAccessor(writeMethod.getModifiers()))
                    publicFields.add(
                        (new StringBuilder(String.valueOf(propertyName)))
                            .append(",")
                            .append(pd.getPropertyType().getName())
                            .toString());
                }
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
            if (publicFields != null && publicFields.size() > 0) {
              String temp = null;
              result.append("<publicFields>");
              for (int counter = 0; counter < publicFields.size(); counter++) {
                temp = (String) publicFields.get(counter);
                if (temp != null) {
                  String pubTemp[] = temp.split(",");
                  if (pubTemp.length == 2) {
                    result.append("<publicField>");
                    result.append(
                        (new StringBuilder("<publicFieldName>"))
                            .append(pubTemp[0])
                            .append("</publicFieldName>")
                            .toString());
                    result.append(
                        (new StringBuilder("<publicFieldType>"))
                            .append(pubTemp[1])
                            .append("</publicFieldType>")
                            .toString());
                    result.append("</publicField>");
                  }
                }
              }

              result.append("</publicFields>");
            }
          } catch (ClassNotFoundException e) {
            result.append(
                (new StringBuilder("<classFullName>"))
                    .append(className)
                    .append("</classFullName>")
                    .toString());
            result.append(
                (new StringBuilder("<error>Problem retrieving "))
                    .append(className)
                    .append(" information</error>")
                    .toString());
            System.out.println(e.getMessage());
          }
          result.append("</classDefinition>");
        }
      }
    }
    result.append("</classDefinitions>");
    return result.toString();
  }
コード例 #20
0
ファイル: Request2.java プロジェクト: jmcclell/h2o
 @Override
 protected String[] errors() {
   if (_type != null) return new String[] {"Key is not a " + _type.getSimpleName()};
   return super.errors();
 }
コード例 #21
0
ファイル: TagReader.java プロジェクト: Mur4ik/dsl4xml
 public ContextMutator(Class<?> aFor, Class<T> aWith, String aTagName) {
   method = Classes.getMutatorMethod(aFor, aWith.getSimpleName(), aTagName);
 }
コード例 #22
0
 public boolean matches(Type type, Annotations annotations) {
   String thisName = getQualifiedName(new StringBuilder(), false).toString();
   Class typeClass = getTypeClass(type);
   String typeName = typeClass.getSimpleName();
   return thisName.equals(typeName) || thisName.equals(typeClass.getName());
 }
コード例 #23
0
  public static void main(String[] args) {

    // Obtain the class object if we know the name of the class
    Class rental = RentCar.class;
    try {
      // get the absolute name of the class
      String rentalClassPackage = rental.getName();
      System.out.println("Class Name is: " + rentalClassPackage);

      // get the simple name of the class (without package info)
      String rentalClassNoPackage = rental.getSimpleName();
      System.out.println("Class Name without package is: " + rentalClassNoPackage);

      // get the package name of the class
      Package rentalPackage = rental.getPackage();
      System.out.println("Package Name is: " + rentalPackage);

      // get all the constructors of the class
      Constructor[] constructors = rental.getConstructors();
      System.out.println("Constructors are: " + Arrays.toString(constructors));

      // get constructor with specific argument
      Constructor constructor = rental.getConstructor(Integer.TYPE);

      // initializing an object of the RentCar class
      RentCar rent = (RentCar) constructor.newInstance(455);

      // get all methods of the class including declared methods of
      // superclasses
      // in that case, superclass of RentCar is the class java.lang.Object
      Method[] allmethods = rental.getMethods();
      System.out.println("Methods are: " + Arrays.toString(allmethods));
      for (Method method : allmethods) {
        System.out.println("method = " + method.getName());
      }

      // get all methods declared in the class
      // but excludes inherited methods.
      Method[] declaredMethods = rental.getDeclaredMethods();
      System.out.println("Declared Methods are: " + Arrays.toString(declaredMethods));
      for (Method dmethod : declaredMethods) {
        System.out.println("method = " + dmethod.getName());
      }

      // get method with specific name and parameters
      Method oneMethod = rental.getMethod("computeRentalCost", new Class[] {Integer.TYPE});
      System.out.println("Method is: " + oneMethod);

      // call computeRentalCost method with parameter int
      oneMethod.invoke(rent, 4);

      // get all the parameters of computeRentalCost
      Class[] parameterTypes = oneMethod.getParameterTypes();
      System.out.println(
          "Parameter types of computeRentalCost() are: " + Arrays.toString(parameterTypes));

      // get the return type of computeRentalCost
      Class returnType = oneMethod.getReturnType();
      System.out.println("Return type is: " + returnType);

      // gets all the public member fields of the class RentCar
      Field[] fields = rental.getFields();

      System.out.println("Public Fields are: ");
      for (Field oneField : fields) {
        // get public field name
        Field field = rental.getField(oneField.getName());
        String fieldname = field.getName();
        System.out.println("Fieldname is: " + fieldname);

        // get public field type
        Object fieldType = field.getType();
        System.out.println("Type of field " + fieldname + " is: " + fieldType);

        // get public field value
        Object value = field.get(rent);
        System.out.println("Value of field " + fieldname + " is: " + value);
      }

      // How to access private member fields of the class

      // getDeclaredField() returns the private field
      Field privateField = RentCar.class.getDeclaredField("type");

      String name = privateField.getName();
      System.out.println("One private Fieldname is: " + name);
      // makes this private field instance accessible
      // for reflection use only, not normal code
      privateField.setAccessible(true);

      // get the value of this private field
      String fieldValue = (String) privateField.get(rent);
      System.out.println("fieldValue = " + fieldValue);

    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
コード例 #24
0
ファイル: Request2.java プロジェクト: jmcclell/h2o
 @Override
 protected String queryDescription() {
   return "A key" + (_type != null ? " of type " + _type.getSimpleName() : "");
 }