Esempio n. 1
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param element The XML element containing the property value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)
        || String.class.isAssignableFrom(type)) {
      return readBasicType(type, element);
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return readDate(element);
    } else {
      try {
        // If it's an object, create a new instance of the object (it should
        // be a bean, or there will be trouble)
        Object newOb = type.newInstance();

        // Copy the XML element into the bean
        readObject(newOb, element);

        return newOb;
      } catch (InstantiationException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      }
    }
  }
Esempio n. 2
0
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
 /**
  * Parses array from given JSONArray. Supports parsing of primitive types and {@link
  * com.vk.sdk.api.model.VKApiModel} instances.
  *
  * @param array JSONArray to parse
  * @param arrayClass type of array field in class.
  * @return object to set to array field in class
  * @throws org.json.JSONException if given array have incompatible type with given field.
  */
 private static Object parseArrayViaReflection(JSONArray array, Class arrayClass)
     throws JSONException {
   Object result = Array.newInstance(arrayClass.getComponentType(), array.length());
   Class<?> subType = arrayClass.getComponentType();
   for (int i = 0; i < array.length(); i++) {
     try {
       Object item = array.opt(i);
       if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) {
         VKApiModel model = (VKApiModel) subType.newInstance();
         item = model.parse((JSONObject) item);
       }
       Array.set(result, i, item);
     } catch (InstantiationException e) {
       throw new JSONException(e.getMessage());
     } catch (IllegalAccessException e) {
       throw new JSONException(e.getMessage());
     } catch (IllegalArgumentException e) {
       throw new JSONException(e.getMessage());
     }
   }
   return result;
 }
  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();
    }
  }
  /**
   * Parses object with follow rules:
   *
   * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to
   * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of
   * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list
   * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or
   * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s.
   *
   * <p>4. Boolean fields defines by vk_int == 1 expression.
   *
   * @param object object to initialize
   * @param source data to read values
   * @param <T> type of result
   * @return initialized according with given data object
   * @throws org.json.JSONException if source object structure is invalid
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
      source = source.optJSONObject("response");
    }
    if (source == null) {
      return object;
    }
    for (Field field : object.getClass().getFields()) {
      field.setAccessible(true);
      String fieldName = field.getName();
      Class<?> fieldType = field.getType();

      Object value = source.opt(fieldName);
      if (value == null) {
        continue;
      }
      try {
        if (fieldType.isPrimitive() && value instanceof Number) {
          Number number = (Number) value;
          if (fieldType.equals(int.class)) {
            field.setInt(object, number.intValue());
          } else if (fieldType.equals(long.class)) {
            field.setLong(object, number.longValue());
          } else if (fieldType.equals(float.class)) {
            field.setFloat(object, number.floatValue());
          } else if (fieldType.equals(double.class)) {
            field.setDouble(object, number.doubleValue());
          } else if (fieldType.equals(boolean.class)) {
            field.setBoolean(object, number.intValue() == 1);
          } else if (fieldType.equals(short.class)) {
            field.setShort(object, number.shortValue());
          } else if (fieldType.equals(byte.class)) {
            field.setByte(object, number.byteValue());
          }
        } else {
          Object result = field.get(object);
          if (value.getClass().equals(fieldType)) {
            result = value;
          } else if (fieldType.isArray() && value instanceof JSONArray) {
            result = parseArrayViaReflection((JSONArray) value, fieldType);
          } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKAttachments.class.isAssignableFrom(fieldType)
              && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKList.class.equals(fieldType)) {
            ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
            Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
            if (VKApiModel.class.isAssignableFrom(genericType)
                && Parcelable.class.isAssignableFrom(genericType)
                && Identifiable.class.isAssignableFrom(genericType)) {
              if (value instanceof JSONArray) {
                result = new VKList((JSONArray) value, genericType);
              } else if (value instanceof JSONObject) {
                result = new VKList((JSONObject) value, genericType);
              }
            }
          } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
            result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
          }
          field.set(object, result);
        }
      } catch (InstantiationException e) {
        throw new JSONException(e.getMessage());
      } catch (IllegalAccessException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodException e) {
        throw new JSONException(e.getMessage());
      } catch (InvocationTargetException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodError e) {
        // Примечание Виталия:
        // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО.
        // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве
        // платформы разработки.
        throw new JSONException(e.getMessage());
      }
    }
    return object;
  }