Example usage for java.lang.reflect Method invoke

List of usage examples for java.lang.reflect Method invoke

Introduction

In this page you can find the example usage for java.lang.reflect Method invoke.

Prototype

@CallerSensitive
@ForceInline 
@HotSpotIntrinsicCandidate
public Object invoke(Object obj, Object... args)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException 

Source Link

Document

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

Usage

From source file:Main.java

public static void killProcesses(Context context, int pid, String processName) {
    /*String cmd = "kill -9 "+pid;
    Process process = null;//from  w w w  .j av a2s .co m
    DataOutputStream os = null;
    try {
      process = Runtime.getRuntime().exec("su"); 
      os = new DataOutputStream(process.getOutputStream());
      os.writeBytes(cmd + "\n");
      os.writeBytes("exit\n");
      os.flush();
      process.waitFor();
    } catch (Exception e) {
      e.printStackTrace();
    }
    AbLogUtil.d(AbAppUtil.class, "#kill -9 "+pid);*/

    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String packageName = null;
    try {
        if (processName.indexOf(":") == -1) {
            packageName = processName;
        } else {
            packageName = processName.split(":")[0];
        }

        activityManager.killBackgroundProcesses(packageName);

        //
        Method forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage",
                String.class);
        forceStopPackage.setAccessible(true);
        forceStopPackage.invoke(activityManager, packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:Main.java

  /**
 * Computes the maximum bounds of the current screen device. If this method is
 * called on JDK 1.4, Xinerama-aware results are returned. (See Sun-Bug-ID
 * 4463949 for details)./* www.  j  a  v a2s  .  c  o  m*/
 * 
 * @return the maximum bounds of the current screen.
 */
public static Rectangle getMaximumWindowBounds() {
  final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment
      .getLocalGraphicsEnvironment();
  try {
    final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds",
        (Class[]) null);
    return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
  } catch (Exception e) {
    // ignore ... will fail if this is not a JDK 1.4 ..
  }

  final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
  return new Rectangle(0, 0, s.width, s.height);
}

From source file:Main.java

public static boolean modifyPermissionAutoStart(Context context, boolean enable) {
    try {//w w w  . ja  v a  2 s. c o  m
        Class cls = Class.forName("android.miui.AppOpsUtils");
        if (cls != null) {
            Method declaredMethod = cls.getDeclaredMethod("setApplicationAutoStart",
                    new Class[] { Context.class, String.class, Boolean.TYPE });
            if (declaredMethod != null) {
                declaredMethod.invoke(cls,
                        new Object[] { context, context.getPackageName(), Boolean.valueOf(enable) });
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:me.j360.dubbo.modules.util.reflect.ReflectionUtil.java

/**
 * Method/*from   w w  w. j av  a 2  s  .co m*/
 */
public static <T> T invokeMethod(final Object obj, Method method, Object... args) {
    try {
        return (T) method.invoke(obj, args);
    } catch (Exception e) {
        throw ExceptionUtil.uncheckedAndWrap(e);
    }
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static Object searchProperty(Object leftParameter, String name) throws Exception {
    Class<?> leftClass = leftParameter.getClass();
    Object result;/*from  w  w  w  .j a  v  a2  s  . c  o  m*/
    if (leftParameter.getClass().isArray() && "length".equals(name)) {
        result = Array.getLength(leftParameter);
    } else if (leftParameter instanceof Map) {
        result = ((Map<Object, Object>) leftParameter).get(name);
    } else {
        try {
            String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = leftClass.getMethod(getter, new Class<?>[0]);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            result = method.invoke(leftParameter, new Object[0]);
        } catch (NoSuchMethodException e2) {
            try {
                String getter = "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = leftClass.getMethod(getter, new Class<?>[0]);
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                result = method.invoke(leftParameter, new Object[0]);
            } catch (NoSuchMethodException e3) {
                Field field = leftClass.getField(name);
                result = field.get(leftParameter);
            }
        }
    }
    return result;
}

From source file:org.zht.framework.util.ZBeanUtil.java

@SuppressWarnings("rawtypes")
public static Object convertMapToBean(Map map, Class<?> type) {
    Object obj = null;/*from ww w .  j  av  a  2 s . co m*/
    try {
        BeanInfo beanInfo = null;

        beanInfo = Introspector.getBeanInfo(type);
        obj = type.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String properName = property.getName();
            if (map.containsKey(property.getName())) {
                try {// ??

                    Object value = map.get(properName);
                    Method setter = property.getWriteMethod();
                    setter.invoke(obj, value);
                    //Unable to find non-private method
                    //               access.invoke(obj,"set" + ZStrUtil.toUpCaseFirst(properName),value);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return obj;
    }
    return obj;
}

From source file:org.vaadin.spring.i18n.Translator.java

private static void setPropertyValue(Object target, String propertyName, String value) {
    final String setterMethodName = "set" + StringUtils.capitalize(propertyName);
    try {/*from  w ww.j  a  v a  2s.c om*/
        final Method setterMethod = target.getClass().getMethod(setterMethodName, String.class);
        setterMethod.invoke(target, value);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("No public setter method found for property " + propertyName);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Could not invoke setter method for property " + propertyName, e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Could not access setter method for property " + propertyName);
    }
}

From source file:de.micromata.genome.gwiki.utils.ClassUtils.java

@SuppressWarnings("unchecked")
public static <T> T invokeDefaultStaticMethod(Class<T> expectedClass, String className, String methodName) {
    Class<?> cls = classForName(className);
    try {/*from ww  w .  j a  va  2s .  c o  m*/
        Method m = cls.getMethod(methodName, new Class[] {});
        T t = (T) m.invoke(null, new Object[] {});
        if (t == null) {
            return t;
        }
        if (expectedClass.isAssignableFrom(t.getClass()) == false) {
            throw new RuntimeException("method: " + methodName + " from class: " + className
                    + " does not return correct class type: " + expectedClass + " but: " + t.getClass());
        }
        return t;
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException("Cannot find method: " + methodName + " in class: " + className);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    } catch (InvocationTargetException ex) {
        Throwable nex = ex.getCause();
        if (nex instanceof RuntimeException) {
            throw (RuntimeException) nex;
        }
        throw new RuntimeException(ex);
    }
}

From source file:com.wxxr.nirvana.ContainerAccess.java

/**
 * Removes an attribute from a context./*from  www  .  j  a v a 2  s  .  co  m*/
 *
 * @param context
 *            The context object to use.
 * @param name
 *            The name of the attribute to remove.
 * @throws NirvanaException
 *             If something goes wrong during removal.
 */
private static void removeAttribute(Object context, String name) throws NirvanaException {
    try {
        Class<?> contextClass = context.getClass();
        Method attrMethod = contextClass.getMethod("removeAttribute", String.class);
        attrMethod.invoke(context, name);
    } catch (Exception e) {
        throw new NirvanaException("Unable to remove attribute for specified context: '" + context + "'");
    }
}

From source file:Main.java

public static Point positionToClickPoint(Container component, int caretPosition, Container invokedIn) {
    if (component == null) {
        return null;
    }//from ww w  .  j a  va2  s  .  c  om

    //System.err.println("Checking: " + component.getClass().getName());
    if (component.getClass().getName().indexOf("EditorPane") >= 0) {
        try {
            java.lang.reflect.Method pointGetter = component.getClass().getMethod("modelToView",
                    new Class[] { Integer.TYPE });
            Rectangle rec = (Rectangle) pointGetter.invoke(component,
                    new Object[] { new Integer(caretPosition) });
            //System.err.println("Before: " + (int)rec.getY());
            // FIXME: somehow it fails here to convert point from scrollable component
            Point point = SwingUtilities.convertPoint(component, (int) rec.getX(), (int) rec.getY() + 10,
                    invokedIn);
            // FIXME: ugly hack :(
            if (point.getY() > 1024) {
                point = new Point((int) point.getX(), 250);
            }
            //System.err.println("After: " + (int)point.getY());
            return point;
        } catch (Exception e) {
            System.err.println("Method invocation exception caught");
            e.printStackTrace();

            //FIXME: BUG
            return null;
            //throw new RuntimeException("Method invocation exception caught");
        }
    }

    for (int i = 0; i < component.getComponentCount(); i++) {
        java.awt.Component childComponent = component.getComponent(i);
        if (childComponent instanceof javax.swing.JComponent) {
            Point point = positionToClickPoint((javax.swing.JComponent) childComponent, caretPosition,
                    invokedIn);
            if (point != null) {
                return point;
            }
        }
    }

    return null;
}