Beispiel #1
0
  @Test
  public void testGetField() {
    assertNull(
        "inexistFileName field shouldn't exist!", ReflectUtil.getField(cls, "inexistFieldName"));

    assertNotNull("name field should exist!", ReflectUtil.getField(cls, "name"));
  }
Beispiel #2
0
  public boolean openSystemBrowser(String url) {
    try {
      for (String command : getOpenCommands()) {
        if (openSystemBrowser(command, url)) {
          return true;
        }
      }
    } catch (Throwable ex) {
      // $FALL-THROUGH$
    }

    try {
      // java.awt.Desktop was introduced with Java 1.6!
      Class<?> desktopClass =
          CommonPlugin.loadClass(UtilPlugin.INSTANCE.getSymbolicName(), "java.awt.Desktop");
      Method getDesktopMethod = ReflectUtil.getMethod(desktopClass, "getDesktop");
      Method browseMethod = ReflectUtil.getMethod(desktopClass, "browse", URI.class);

      Object desktop = getDesktopMethod.invoke(null);
      browseMethod.invoke(desktop, new URI(url));
      return true;
    } catch (Throwable ex) {
      UtilPlugin.INSTANCE.log(ex, IStatus.WARNING);
    }

    return false;
  }
Beispiel #3
0
  @Test
  public void testGetFieldValue() {
    assertEquals(null, ReflectUtil.getFieldValue("id", obj1, null));
    assertEquals(null, ReflectUtil.getFieldValue("name", obj1, null));

    assertEquals(2, ReflectUtil.getFieldValue("i", obj2, null));
    assertEquals("Will", ReflectUtil.getFieldValue("name", obj2, null));
  }
Beispiel #4
0
 public static String matchDeclaringTypeName(JavaType sourceType) {
   Type candidateType = matchDeclaringType(sourceType);
   if (candidateType instanceof TypeNameWrapper) {
     return TypeNameWrapper.class.cast(candidateType).getTypeName();
   }
   Class rawType = ReflectUtil.getRawClass(candidateType);
   return rawType.getName();
 }
  @Test
  public void testBuildReflectInfoBaseClass() {
    String[] names = {"id", "userName"};
    int[] types = {JavaTypes.STRING, JavaTypes.STRING};

    ReflectInfo info = ReflectUtil.buildReflectInfo(BasicUser.class);
    performTest(info, names, types);
  }
 public static AntClassLoader newAntClassLoader(
     final ClassLoader parent, final Project project, final Path path, final boolean parentFirst) {
   if (AntClassLoader.subClassToLoad != null) {
     return ReflectUtil.newInstance(
         AntClassLoader.subClassToLoad,
         AntClassLoader.CONSTRUCTOR_ARGS,
         new Object[] {parent, project, path, parentFirst});
   }
   return new AntClassLoader(parent, project, path, parentFirst);
 }
 /**
  * Construct a wrapped object using the no arg constructor.
  *
  * @param loader the classloader to use to construct the class.
  * @param name the classname of the object to construct.
  */
 public ReflectWrapper(ClassLoader loader, String name) {
   try {
     Class clazz;
     clazz = Class.forName(name, true, loader);
     Constructor constructor;
     constructor = clazz.getConstructor((Class[]) null);
     obj = constructor.newInstance((Object[]) null);
   } catch (Exception t) {
     ReflectUtil.throwBuildException(t);
   }
 }
Beispiel #8
0
  public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("age", 12);
    map.put("name", "刘诗诗");
    User user = new User();
    BeanUtils.populate(user, map);
    ReflectUtil.printBean(user);

    System.out.println(new BeanMap(user));
  }
 /**
  * 利用反射设置指定对象的指定属性为指定的值
  *
  * @param obj 目标对象
  * @param fieldName 目标属性
  * @param fieldValue 目标值
  */
 public static void setFieldValue(Object obj, String fieldName, String fieldValue) {
   Field field = ReflectUtil.getField(obj, fieldName);
   if (field != null) {
     try {
       field.setAccessible(true);
       field.set(obj, fieldValue);
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     }
   }
 }
  @Test
  public void testBuildReflectInfoSubClass() {
    String[] names = {"amount", "created", "emailAddress", "id", "memo", "userName"};
    int[] types = {
      JavaTypes.DOUBLE,
      JavaTypes.TIMESTAMP_SQL,
      JavaTypes.STRING,
      JavaTypes.STRING,
      JavaTypes.STRING,
      JavaTypes.STRING
    };

    ReflectInfo info = ReflectUtil.buildReflectInfo(User.class);
    performTest(info, names, types);
  }
 /**
  * 利用反射获取指定对象的指定属性
  *
  * @param obj 目标对象
  * @param fieldName 目标属性
  * @return 目标属性的值
  */
 public static Object getFieldValue(Object obj, String fieldName) {
   Object result = null;
   Field field = ReflectUtil.getField(obj, fieldName);
   if (field != null) {
     field.setAccessible(true);
     try {
       result = field.get(obj);
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     }
   }
   return result;
 }
Beispiel #12
0
  public void read(StructureReader ins) throws IOException {
    int ncomponents = ins.readInt();
    components = new GEdge[ncomponents];
    weights = new double[ncomponents];

    for (int i = 0; i < components.length; i++) {
      weights[i] = ins.readDouble();
      String cls = ins.readString();
      components[i] = (GEdge) ReflectUtil.createObject(cls);
      ins.blockBegin();
      components[i].read(ins);
      ins.blockEnd();
    }

    attributes = Attributes.read(ins);

    nodes = LinAlg.copy(components[0].nodes);
  }
Beispiel #13
0
 public static boolean matchFieldMethods(Type candidate, Collection<JavaMethod> methods) {
   if (candidate instanceof TypeNameWrapper) {
     return true;
   }
   Class rawClass = ReflectUtil.getRawClass(candidate);
   JavaType candidateType = new ClassTypeProvider(rawClass).get();
   Set<String> candidateMethods = new HashSet<String>();
   for (JavaMethod method : candidateType.getMethods()) {
     candidateMethods.add(method.getName());
   }
   for (JavaMethod method : methods) {
     String methodName = method.getName();
     if (methodName.length() > 3
         && (methodName.startsWith("get") || methodName.startsWith("is"))) {
       if (!candidateMethods.contains(methodName)) {
         return false;
       }
     }
   }
   return true;
 }
 public void loadAgent(final String agent, final String options) {
   ReflectUtil.callMethod(
       wrapped, "loadAgent", new Class<?>[] {String.class, String.class}, agent, options);
 }
 public Properties getSystemProperties() {
   return ReflectUtil.callMethod(wrapped, "getSystemProperties", new Class<?>[0]);
 }
 @Override
 public void close() {
   ReflectUtil.callMethod(wrapped, "detach", new Class<?>[0]);
 }
  @Override
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Object intercept(Invocation invocation) throws Throwable {
    if (invocation.getTarget() instanceof StatementHandler) { // 控制SQL和查询总数的地方
      Page page = pageThreadLocal.get();
      Order order = orderThreadLocal.get();
      RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();
      StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");
      BoundSql boundSql = delegate.getBoundSql();
      if (page == null) { // 不是分页查询
        if (order != null) {
          String orderSql = buildOrderSql(order, boundSql.getSql());
          ReflectUtil.setFieldValue(boundSql, "sql", orderSql);
        }
        return invocation.proceed();
      }

      Connection connection = (Connection) invocation.getArgs()[0];
      prepareAndCheckDatabaseType(connection); // 准备数据库类型

      if (page.getTotalPage() > -1) {
        if (log.isTraceEnabled()) {
          log.trace("已经设置了总页数, 不需要再查询总数.");
        }
      } else {
        Object parameterObj = boundSql.getParameterObject();
        MappedStatement mappedStatement =
            (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");
        queryTotalRecord(page, parameterObj, mappedStatement, connection);
      }

      String sql = boundSql.getSql();
      if (order != null) {
        sql = buildOrderSql(order, sql);
      }
      String pageSql = buildPageSql(page, sql);
      if (log.isDebugEnabled()) {
        log.debug("分页时, 生成分页pageSql: " + pageSql);
      }
      ReflectUtil.setFieldValue(boundSql, "sql", pageSql);

      return invocation.proceed();
    } else { // 查询结果的地方
      try {
        // 获取是否有分页Page对象
        Page<?> page = findPageObject(invocation.getArgs()[1]);
        // 获取是否有排序Order对象
        Order order = findOrderObject(invocation.getArgs()[1]);
        if (order != null) {
          orderThreadLocal.set(order);
        }
        if (page == null) {
          if (log.isTraceEnabled()) {
            log.trace("没有Page对象作为参数, 不是分页查询.");
          }
          return invocation.proceed();
        } else {
          if (log.isTraceEnabled()) {
            log.trace("检测到分页Page对象, 使用分页查询.");
          }
        }
        // 设置真正的parameterObj
        invocation.getArgs()[1] = extractRealParameterObject(invocation.getArgs()[1]);

        pageThreadLocal.set(page);
        Object resultObj = invocation.proceed(); // Executor.query(..)
        if (resultObj instanceof List) {
          /* @SuppressWarnings({ "unchecked", "rawtypes" }) */
          page.setDatas((List) resultObj);
        }
        return resultObj;
      } finally {
        pageThreadLocal.remove();
        orderThreadLocal.remove();
      }
    }
  }
Beispiel #18
0
  @Override
  public void generate(
      Field field, List<String> imports, StringBuilder builder, String name, Method method) {
    Class<?> elementType = null;

    if (!Class.class.isInstance(field.getGenericType())) {
      ParameterizedType paramType = (ParameterizedType) field.getGenericType();
      if (paramType.getActualTypeArguments().length > 0) {
        elementType = (Class<?>) paramType.getActualTypeArguments()[0];
        importClazz(imports, elementType);
      }
    }

    if (field.getType().isInterface()) {
      builder.append("List");
      if (elementType != null) {
        builder.append("<").append(elementType.getSimpleName()).append(">");
      }
      builder.append(" list = null;");
      builder.append('\n');
    } else {
      builder.append(((Class<?>) field.getType()).getSimpleName());
      if (elementType != null) {
        builder.append("<").append(elementType.getSimpleName()).append(">");
      }
      builder.append(" list = null;");
      builder.append('\n');
    }

    try {
      Method getter = ReflectUtil.getGetterMethod(field.getDeclaringClass(), field);
      if (getter != null) {
        builder.append("\t\t\t");
        builder.append("list = object.").append(getter.getName()).append("();");
        builder.append('\n');
      }
    } catch (Exception e) {
    }

    builder.append("\t\t\t");
    builder.append("if(list == null) list = new ");
    if (field.getType().isInterface()) {
      builder.append("ArrayList");
    } else {
      builder.append(((Class<?>) field.getType()).getSimpleName());
    }
    if (elementType != null) {
      builder.append("<").append(elementType.getSimpleName()).append(">");
    }
    builder.append("();");
    builder.append('\n');

    builder.append("\t\t\t");
    builder.append("XML2Object.getInstance().mapCollection(list, ");
    if (elementType != null) {
      builder.append(elementType.getSimpleName()).append(".class");
    } else {
      builder.append("null");
    }
    builder.append(", node);");
    builder.append('\n');

    //    System.out.println(" ====================  > "+ elementType);
    //    System.out.println(" da thu cai nau "+ fields[i].getType());
    builder.append("\t\t\t");
    if (method == null) {
      builder.append("object.").append(name).append("=list;");
    } else {
      builder.append("object.").append(method.getName()).append("(list);");
    }
  }
Beispiel #19
0
 /**
  * Creates a RelFieldTrimmer.
  *
  * @param validator Validator
  */
 public RelFieldTrimmer(SqlValidator validator) {
   Util.discard(validator); // may be useful one day
   this.trimFieldsDispatcher =
       ReflectUtil.createMethodDispatcher(
           TrimResult.class, this, "trimFields", RelNode.class, BitSet.class, Set.class);
 }
 public String id() {
   return ReflectUtil.callMethod(wrapped, "id", new Class<?>[0]);
 }
 public String startLocalManagementAgent() {
   return ReflectUtil.callMethod(wrapped, "startLocalManagementAgent", new Class<?>[0]);
 }
 /**
  * Call a method on the object with one argument.
  *
  * @param methodName the name of the method to call
  * @param argType1 the type of the first argument.
  * @param arg1 the value of the first argument.
  * @param argType2 the type of the second argument.
  * @param arg2 the value of the second argument.
  * @return the object returned by the method
  */
 public Object invoke(
     String methodName, Class argType1, Object arg1, Class argType2, Object arg2) {
   return ReflectUtil.invoke(obj, methodName, argType1, arg1, argType2, arg2);
 }
 /**
  * Call a method on the object with one argument.
  *
  * @param methodName the name of the method to call
  * @param argType the type of argument.
  * @param arg the value of the argument.
  * @return the object returned by the method
  */
 public Object invoke(String methodName, Class argType, Object arg) {
   return ReflectUtil.invoke(obj, methodName, argType, arg);
 }
Beispiel #24
0
 public static JavaMethod matchFirstFieldByType(Type ownerType, Type matchingType) {
   Class rawOwnerType = ReflectUtil.getRawClass(ownerType);
   JavaType javaOwnerType = new ClassTypeProvider(rawOwnerType).get();
   return matchFirstAccessorByType(javaOwnerType, matchingType);
 }
Beispiel #25
0
 /** @param args */
 public static void main(String[] args) {
   ReflectUtil ru = new ReflectUtil();
   Class<? extends ReflectUtil> keyClass = ru.getClass(); // 对象所属的类或接口
   System.err.print(keyClass.getName()); // 类名字符串
 }
 /**
  * Call a method on the object with no parameters.
  *
  * @param methodName the name of the method to call
  * @return the object returned by the method
  */
 public Object invoke(String methodName) {
   return ReflectUtil.invoke(obj, methodName);
 }
 /**
  * Creates a new FarragoReduceExpressionsRule object.
  *
  * @param relClass class of rels to which this rule should apply
  */
 private FarragoReduceExpressionsRule(Class<? extends RelNode> relClass) {
   super(
       new RelOptRuleOperand(relClass, ANY),
       "FarragoReduceExpressionsRule:" + ReflectUtil.getUnqualifiedClassName(relClass));
 }