vendredi 17 juillet 2015

getLastLocation using Reflection with GoogleApiClient and LocationServices

I'm working on an Android Library and I need to remove the play services dependencies to be added by the developer who used my library. I need user location last location so I need to use reflection because the location library will not be included directly in my library.

But how to create the googleApiClient from the builder via reflection ?

I already a general method to invoke class methods via reflection :

/**
 * Invokes a static method within a class
 * if it can be found on the classpath.
 *
 * @param className The full defined classname
 * @param methodName The name of the method to invoke
 * @param cArgs The args that the method can take
 * @param args The args to pass to the method on invocation
 * @return the result of the method invoke
 * @throws Exception
 */
private Object invokeStaticMethod(String className, String methodName,
                                  Class[] cArgs, Object... args) throws Exception {
    Class classObject = Class.forName(className);
    return invokeMethod(classObject, methodName, null, cArgs, args);
}

/**
 * Invokes a method on a static instance
 * within a class by reflection.
 *
 * @param instance The instance to invoke a method on
 * @param methodName The name of the method to invoke
 * @param cArgs The args that the method can take
 * @param args The args to pass to the method on invocation
 * @return the result of the method invoke
 * @throws Exception
 */
private Object invokeInstanceMethod(Object instance, String methodName,
                                    Class[] cArgs, Object... args) throws Exception {
    Class classObject = instance.getClass();
    return invokeMethod(classObject, methodName, instance, cArgs, args);
}

/**
 * Invokes methods of a class via reflection
 *
 * @param classObject The class to attempt invocation on
 * @param methodName The name of the method to invoke
 * @param instance The object instance to invoke on
 * @param cArgs The args that the method can take
 * @param args The args to pass to the method on invocation
 * @return the result of the method invoke
 * @throws Exception
 */
private Object invokeMethod(Class classObject, String methodName, Object instance,
                            Class[] cArgs, Object... args) throws Exception {
    Method methodObject = classObject.getMethod(methodName, cArgs);
    return methodObject.invoke(instance, args);
}





Aucun commentaire:

Enregistrer un commentaire