示例#1
1
 /**
  * Retrieve the names of all the public static classes in the clazz
  *
  * @param clazz the object to inspect
  * @return list of all the names of public statics
  */
 public String[] getPublicStaticClassNames(Class<?> clazz) {
   Class<?>[] classes = clazz.getClasses();
   Set<String> classNames = new HashSet<String>();
   for (Class<?> clazz2 : classes) {
     if (Modifier.isPublic(clazz2.getModifiers()) && Modifier.isStatic(clazz2.getModifiers())) {
       classNames.add(clazz2.getSimpleName());
     }
   }
   return (String[]) classNames.toArray(new String[classNames.size()]);
 }
 /** INTERNAL: Load a class from a given class name. (XMLEntityMappings calls this one) */
 public static Class getClassForName(String classname, ClassLoader loader) {
   try {
     if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
       try {
         return (Class)
             AccessController.doPrivileged(new PrivilegedClassForName(classname, true, loader));
       } catch (PrivilegedActionException exception) {
         throw ValidationException.unableToLoadClass(classname, exception.getException());
       }
     } else {
       return PrivilegedAccessHelper.getClassForName(classname, true, loader);
     }
   } catch (ClassNotFoundException exception) {
     if (classname.indexOf('$') != -1) {
       String outer = classname.substring(0, classname.indexOf('$'));
       Class outerClass = getClassForName(outer, loader);
       for (int index = 0; index < outerClass.getClasses().length; index++) {
         if (outerClass.getClasses()[index].getName().equals(classname)) {
           return outerClass.getClasses()[index];
         }
       }
     }
     throw ValidationException.unableToLoadClass(classname, exception);
   }
 }
  private Class<?> getNestedClass(Class<?> clazz, String nested) {
    for (Class<?> nestedClass : clazz.getClasses()) {
      if (nestedClass.getSimpleName().equals(nested)) return nestedClass;
    }

    throw new AssertionError("No such nested class: " + nested);
  }
示例#4
0
  public boolean endCall() {
    if (_prevRingerMode == null) {
      _prevRingerMode = _audioManager.getRingerMode();
    }

    _audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

    try {
      String serviceManagerName = "android.os.ServiceManager";
      String serviceManagerNativeName = "android.os.ServiceManagerNative";
      String telephonyName = "com.android.internal.telephony.ITelephony";

      Class<?> telephonyClass = Class.forName(telephonyName);
      Class<?> telephonyStubClass = telephonyClass.getClasses()[0];
      Class<?> serviceManagerClass = Class.forName(serviceManagerName);
      Class<?> serviceManagerNativeClass = Class.forName(serviceManagerNativeName);

      Binder tmpBinder = new Binder();
      tmpBinder.attachInterface(null, "fake");
      Method tempInterfaceMethod =
          serviceManagerNativeClass.getMethod("asInterface", IBinder.class);
      Object serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
      Method getService = serviceManagerClass.getMethod("getService", String.class);
      IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");

      Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
      Object telephonyObject = serviceMethod.invoke(null, retbinder);
      Method telephonyEndCall = telephonyClass.getMethod("endCall");
      telephonyEndCall.invoke(telephonyObject);
      return true;
    } catch (Exception e) {
      Log.e(TAG, "Could not connect to telephony subsystem", e);
      return false;
    }
  }
  public static int getResourseIdByName(String packageName, String className, String name) {
    Class r = null;
    int id = 0;
    try {
      r = Class.forName(packageName + ".R");

      Class[] classes = r.getClasses();
      Class desireClass = null;

      for (int i = 0; i < classes.length; i++) {
        if (classes[i].getName().split("\\$")[1].equals(className)) {
          desireClass = classes[i];

          break;
        }
      }

      if (desireClass != null) id = desireClass.getField(name).getInt(desireClass);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    }

    return id;
  }
 public void testCreateInstanceWithReflection() throws Exception {
   Class klass = Class.forName("org.openehr.schemas.v1.DVTEXT");
   Class factoryClass = klass.getClasses()[0];
   Method factoryMethod = factoryClass.getMethod("newInstance", null);
   Object obj = factoryMethod.invoke(null, null);
   assertTrue(obj instanceof DVTEXT);
 }
  public void testCallSetterWithReflection() throws Exception {
    Class klass = Class.forName("org.openehr.schemas.v1.DVTEXT");
    Class factoryClass = klass.getClasses()[0];
    Method factoryMethod = factoryClass.getMethod("newInstance", null);
    Object obj = factoryMethod.invoke(null, null);
    Method setterMethod = klass.getMethod("setValue", String.class);
    setterMethod.invoke(obj, "new value");

    assertEquals("new value", ((DVTEXT) obj).getValue());
  }
示例#8
0
  private void analyzeJaxbClasses(
      Set<String> xmlRootElements, Map<String, Class<?>> entityClasses) {
    for (Class<?> jaxbClass : jaxbClasses) {
      final String xmlRootElement = jaxbClass.getAnnotation(XmlRootElement.class).name();
      xmlRootElements.add(xmlRootElement);

      for (Class<?> entityClass : jaxbClass.getClasses()) {
        entityClasses.put(entityClass.getSimpleName(), entityClass);
      }
    }
  }
 public static void test(Class<?> surroundingClass) {
   for (Class<?> type : surroundingClass.getClasses()) {
     System.out.print(type.getSimpleName() + ": ");
     try {
       Generator<?> g = (Generator<?>) type.newInstance();
       for (int i = 0; i < size; i++) System.out.printf(g.next() + " ");
       System.out.println();
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
示例#10
0
  public Class<?> getClass(Class<?> clazz, String name) {
    Class<?> memberClass = null;

    try {
      for (Class<?> tempClass : clazz.getClasses()) {
        if (tempClass.getSimpleName().equals(name)) {
          memberClass = tempClass;
          break;
        }
      }
    } catch (Exception e) {
      memberClass = null;
    }

    return memberClass;
  }
示例#11
0
  /**
   * Recursively finds inner classes of the specified access level in the supplied class and
   * superclasses.
   *
   * @param c the class to start the search in - nothing is done if this is NULL
   * @param level the access level to look for
   * @param sb the StringBuffer where the results should be added
   */
  private static void recursiveListInnerClasses(Class c, int level, StringBuffer sb) {
    if (c == null) {
      return;
    }

    Class[] innerClasses;
    Class innerClass;
    String clas;

    // ----- Added by Petter for interfaces
    if (level == PUBLIC) {
      // For public access, we can use getClasses() and skip
      // recursion. This ensures that the method works for
      // interface types, and saves some function calls.  XXX -
      // actually, this doesn't work properly, since classes
      // defined in interfaces don't show up here.
      innerClasses = c.getClasses();
    } else {
      innerClasses = c.getDeclaredClasses();
    }
    // ----- End addition by Petter

    for (int index = 0; index < innerClasses.length; index++) {
      innerClass = innerClasses[index];
      if (isAccessible(innerClass.getModifiers(), level)) {
        clas = printClass(innerClass.getName());
        if (sb.toString().lastIndexOf(clas) == -1) {
          sb.append(clas);
        }
      }
    }

    // ----- Addition by Petter to reduce the number of function
    //       calls and not list non-accessible private fields.
    if (!c.isInterface() && level != PRIVATE && level != PUBLIC) {
      // For interfaces, the getSuperClass() method will return
      // nil, and in any case, the only type of access relevant
      // for interfaces is PUBLIC. For PUBLIC access, the
      // getClasses() call has listed all the relevant members.
      // For PRIVATE access, that is only applicable in the
      // calling class anyway, so we shouldn't do recursion.
      recursiveListInnerClasses(c.getSuperclass(), level, sb);
    }
    // ----- End addition by Petter
  }
  /**
   * Gets the evaluator class for the UDAF given the parameter types.
   *
   * @param argClasses The list of the parameter types.
   */
  public Class<? extends UDAFEvaluator> getEvaluatorClass(List<TypeInfo> argClasses)
      throws UDFArgumentException {

    ArrayList<Class<? extends UDAFEvaluator>> classList =
        new ArrayList<Class<? extends UDAFEvaluator>>();

    // Add all the public member classes that implement an evaluator
    for (Class<?> enclClass : udafClass.getClasses()) {
      if (UDAFEvaluator.class.isAssignableFrom(enclClass)) {
        classList.add((Class<? extends UDAFEvaluator>) enclClass);
      }
    }

    // Next we locate all the iterate methods for each of these classes.
    ArrayList<Method> mList = new ArrayList<Method>();
    ArrayList<Class<? extends UDAFEvaluator>> cList =
        new ArrayList<Class<? extends UDAFEvaluator>>();
    for (Class<? extends UDAFEvaluator> evaluator : classList) {
      for (Method m : evaluator.getMethods()) {
        if (m.getName().equalsIgnoreCase("iterate")) {
          mList.add(m);
          cList.add(evaluator);
        }
      }
    }

    Method m = FunctionRegistry.getMethodInternal(udafClass, mList, false, argClasses);

    // Find the class that has this method.
    // Note that Method.getDeclaringClass() may not work here because the method
    // can be inherited from a base class.
    int found = -1;
    for (int i = 0; i < mList.size(); i++) {
      if (mList.get(i) == m) {
        if (found == -1) {
          found = i;
        } else {
          throw new AmbiguousMethodException(udafClass, null, null);
        }
      }
    }
    assert (found != -1);

    return cList.get(found);
  }
示例#13
0
 /**
  * Load all classes that implement <code>Converter</code> and are contained in <code>
  * containerClass</code>.
  *
  * @param containerClass
  */
 public static void loadContainedConverters(Class<?> containerClass) {
   // This only returns -public- classes and interfaces
   for (Class<?> clz : containerClass.getClasses()) {
     try {
       // non-abstract, which means no interfaces or abstract classes
       if ((clz.getModifiers() & Modifier.ABSTRACT) == 0) {
         Object value;
         try {
           value = clz.getConstructor().newInstance();
         } catch (NoSuchMethodException e) {
           // ignore this, as this class might be some other helper class,
           // with a non-pubilc constructor
           continue;
         }
         if (value instanceof ConverterLoader) {
           ConverterLoader loader = (ConverterLoader) value;
           loader.loadConverters();
         }
       }
     } catch (Exception e) {
       Debug.logError(e, module);
     }
   }
 }
示例#14
0
  /**
   * Binds data from reference model instance to XML binding classes
   *
   * @param obj
   * @return
   * @throws XMLBindingException
   */
  public Object bindToXML(Object obj) throws XMLBindingException {
    if (obj == null) {
      return null;
    }
    String className = obj.getClass().getSimpleName();
    Method[] methods = obj.getClass().getMethods();

    try {
      Class xmlClass = Class.forName(XML_BINDING_PACKAGE + className.toUpperCase());

      // debug code only
      if (xmlClass.getClasses().length != 1) {
        log.debug("XMLBinding: bindToXML(): xmlClass.getClass()=" + xmlClass.getClass());
        log.debug("XMLBinding: bindToXML(): xmlClass.toString()=" + xmlClass.toString());
        for (Class clazz : xmlClass.getClasses()) {
          log.debug("\t clazz.getClass()=" + clazz.getClass());
          log.debug("\t clazz.toString()=" + clazz.toString());
        }
      }

      Class factoryClass = xmlClass.getClasses()[0];

      // ES modification: Add xmlOptions containing openehr (default) and xsi namespaces

      // Method factoryMethod = factoryClass.getMethod(NEW_INSTANCE, null);
      // Changed to pick the method with an XmlOptions parameter instead
      Method factoryMethod = factoryClass.getMethod(NEW_INSTANCE, XmlOptions.class);

      // First prameter null because it's a static method, see:
      // http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html
      // Second parameter should be the parameter of XmlObject.Factory.newInstance(XmlOptions
      // options)
      // see:
      // http://xmlbeans.apache.org/docs/2.2.0/reference/org/apache/xmlbeans/XmlObject.Factory.html
      //
      // Previous code was: Object xmlObj = factoryMethod.invoke(null, null);
      Object xmlObj = factoryMethod.invoke(null, xopt);

      Map<String, Class> attributes = builder.retrieveAttribute(className);
      Set<String> attributeNames = attributes.keySet();
      Object attributeValue = null;
      Method setterMethod = null;

      for (Method method : methods) {
        String name = method.getName();

        // cause dead-loop
        if ("getParent".equals(name)) {
          continue; //
        }

        if (isGetter(name, attributeNames)) {

          log.debug("getter: " + name);

          if (method.getParameterTypes().length > 0) {
            continue;
          }

          attributeValue = method.invoke(obj, null);

          if (attributeValue == null) {
            continue;
          }

          log.debug("value.class: " + attributeValue.getClass());

          boolean isList = false;

          if (attributeValue.getClass().isArray()) {
            Object[] array = (Object[]) attributeValue;
            if (array.length == 0) {
              continue;
            }
            Object[] done = new Object[array.length];
            for (int i = 0; i < array.length; i++) {
              done[i] = bindToXML(array[i]);
            }
            attributeValue = done;

          } else if (ProportionKind.class.equals(attributeValue.getClass())) {

            ProportionKind kind = (ProportionKind) attributeValue;
            attributeValue = BigInteger.valueOf(kind.getValue());

          } else if (isOpenEHRRMClass(attributeValue)) {

            attributeValue = bindToXML(attributeValue);

          } else if (List.class.isAssignableFrom(attributeValue.getClass())) {

            isList = true;
            List list = (List) attributeValue;

            log.debug("list.size: " + list.size());

            String attributeName = getAttributeNameFromGetter(name);
            setterMethod = findSetter(attributeName, xmlClass, isList);

            Method addNew = findAddNew(attributeName, xmlClass);

            log.debug("setter: " + setterMethod.getName() + ", xmlClass: " + xmlClass);

            for (int i = 0, j = list.size() - 1; i <= j; i++) {
              Object value = list.get(i);

              Object[] array = new Object[2];

              addNew.invoke(xmlObj, null);

              array[0] = new Integer(i);
              array[1] = bindToXML(value);
              setterMethod.invoke(xmlObj, array);

              log.debug("list.member value set!!!!");
            }
          }

          if (!isList) {
            String attributeName = getAttributeNameFromGetter(name);

            log.debug(
                "attribute: "
                    + attributeName
                    + ", value("
                    + attributeValue
                    + "), "
                    + "type: "
                    + attributeValue.getClass());

            // TODO fix for mismatched attribute name in XSD and RM
            if ("nullFlavor".equals(attributeName)) {
              attributeName = "nullFlavour";
            }

            // skip function according to specs
            if ("isMerged".equals(attributeName)) {
              continue;
            }

            setterMethod = findSetter(attributeName, xmlClass, isList);

            if (setterMethod == null) {
              log.error(
                  "failed to find setterMethod for attribute: "
                      + attributeName
                      + " with type: "
                      + xmlClass);
              continue;
            }

            // special handling deals with 'real' typed
            // attributes in specs but typed 'float' in xsd
            String setter = setterMethod.getName();
            if ("setAccuracy".equals(setter)
                || "setDenominator".equals(setter)
                || "setNumerator".equals(setter)) {

              Double d = (Double) attributeValue;
              attributeValue = d.floatValue();
            }

            log.debug(
                "setter: "
                    + setterMethod.getName()
                    + ", xmlClass: "
                    + xmlClass
                    + ", attributeValue: "
                    + attributeValue
                    + ", attributeValue.class: "
                    + attributeValue.getClass());

            setterMethod.invoke(xmlObj, attributeValue);
          }
        }
      }

      return xmlObj;

    } catch (Exception e) {
      e.printStackTrace();
      throw new XMLBindingException(
          "exception caught when bind obj to " + className + ", " + e.getMessage());
    }
  }
 private static void test(Class<?> c) throws Exception {
   /* Every public nested class represents a test.  In each case, either
    * the class contains further nested classes, in which case we
    * call this method recursively; or it declares or inherits a
    * method called getThing() and it declares a static field
    * called "expect" which
    * is the Type of that method's return value.  The test consists
    * of checking that the value returned by
    * TypeResolver.resolveInClass is indeed this Type.
    */
   System.out.println("Test " + c);
   Class<?>[] nested = c.getClasses();
   Arrays.sort(nested, classNameComparator);
   for (Class<?> n : nested) test(n);
   final Method m;
   try {
     m = c.getMethod("getThing");
   } catch (NoSuchMethodException e) {
     if (nested.length == 0) {
       System.out.println(
           "TEST ERROR: class "
               + c.getName()
               + " has neither "
               + "nested classes nor getThing() method");
       failedCases.add(c);
     }
     return;
   }
   Object expect = null;
   try {
     Field f = c.getDeclaredField("expect");
     expect = f.get(null);
   } catch (NoSuchFieldException e) {
     Class<?> outer = c.getDeclaringClass();
     if (outer != null) {
       try {
         Field f = outer.getDeclaredField("expect" + c.getSimpleName());
         expect = f.get(null);
       } catch (NoSuchFieldException e1) {
       }
     }
   }
   if (expect == null) {
     System.out.println(
         "TEST ERROR: class " + c.getName() + " has getThing() method " + "but not expect field");
     failedCases.add(c);
     return;
   }
   Type t = m.getGenericReturnType();
   //        t = FixType.fixType(t, c);
   t = TypeResolver.resolveInClass(c, t);
   System.out.print("..." + t);
   // check expected value, and incidentally equals method defined
   // by private implementations of the various Type interfaces
   if (expect.equals(t) && t.equals(expect)) System.out.println(", as expected");
   else if ((expect.equals(t) || t.equals(expect)) && expect.toString().equals(t.toString()))
     System.out.println(", as workaround of the 8023301 bug");
   else {
     System.out.println(" BUT SHOULD BE " + expect);
     failedCases.add(c);
   }
 }
示例#16
0
 /** get all declared classes (inner types) of the specified class and all its super classes */
 public static Class[] getDeclaredPublicClasses(Class c) {
   return c.getClasses();
 }
示例#17
0
 private void addNestedClasses(Class<?> clazz, Set<Class<?>> result) {
   for (Class<?> c : clazz.getClasses()) {
     result.add(c);
     addNestedClasses(c, result);
   }
 }