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

/**
 * Returns the value in the current thread's copy of this
 * thread-local variable.  If the variable has no value for the
 * current thread, it is first initialized to the value returned
 * by an invocation of the {@link #initialValue} method.
 *
 * @return the current thread's value of this thread-local
 * @throws NoSuchMethodException //from   w  ww. j  a v a2s.c  o  m
 * @throws SecurityException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws NoSuchFieldException 
 */
@SuppressWarnings("unchecked")
public static <T extends Object> T get(Thread thread, ThreadLocal<T> threadLocal)
        throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchFieldException {
    Object map = getMap(thread); // ThreadLocalMap
    if (map != null) {
        // calling getEntry returns a ThreadLocal.Entry instance, which is a
        // mapping from a ThreadLocal to an Entry, and an Entry is an 
        // extension of WeakReference.
        // ThreadLocalMap.Entry e = map.getEntry(this);
        Method getEntryMethod = map.getClass().getDeclaredMethod("getEntry", new Class[] { ThreadLocal.class });
        getEntryMethod.setAccessible(true);
        Object entry = getEntryMethod.invoke(map, new Object[] { threadLocal }); // ThreadLocalMap.Entry

        if (entry != null) {
            Field valueField = entry.getClass().getDeclaredField("value");
            valueField.setAccessible(true);
            return (T) valueField.get(entry);
        }
    }
    return setInitialValue(thread, threadLocal);
}

From source file:Main.java

public static String[] getRevokedPerms(String packageName, Context ctx) {
    String[] revokedPerms = null;
    PackageManager pkgManager = ctx.getPackageManager();
    Method getRevokedPermissions;
    try {/*from   w  ww .  j  a  v  a  2s . c om*/
        getRevokedPermissions = pkgManager.getClass().getMethod("getRevokedPermissions",
                java.lang.String.class);
        Object[] params = new Object[] { packageName };
        revokedPerms = (String[]) getRevokedPermissions.invoke(pkgManager, params);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return revokedPerms;
}

From source file:ClassUtils.java

/**
 * Helper for invoking an instance method that takes a single parameter.
 * This method also handles parameters of primitive type.
 * //from  www  . j  a va 2 s  .c o  m
 * @param cl
 *            The class that the instance belongs to
 * @param instance
 *            The object on which we will invoke the method
 * @param methodName
 *            The method name
 * @param param
 *            The parameter
 * @throws Throwable
 */
public static Object invokeMethod(Class cl, Object instance, String methodName, Object param) throws Throwable {
    Class paramClass;
    if (param instanceof Integer)
        paramClass = Integer.TYPE;
    else if (param instanceof Long)
        paramClass = Long.TYPE;
    else if (param instanceof Short)
        paramClass = Short.TYPE;
    else if (param instanceof Boolean)
        paramClass = Boolean.TYPE;
    else if (param instanceof Double)
        paramClass = Double.TYPE;
    else if (param instanceof Float)
        paramClass = Float.TYPE;
    else if (param instanceof Character)
        paramClass = Character.TYPE;
    else if (param instanceof Byte)
        paramClass = Byte.TYPE;
    else
        paramClass = param.getClass();
    Method method = cl.getMethod(methodName, new Class[] { paramClass });
    try {
        return method.invoke(instance, new Object[] { param });
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}

From source file:com.microsoft.tfs.client.common.ui.helpers.WorkingSetHelper.java

public static void addToWorkingSet(final IProject project, final IWorkingSet workingSet) {
    try {/*from   www.  j  ava  2s .co m*/
        boolean aggregateWorkingSetAvailable = false;

        try {
            aggregateWorkingSetAvailable = (Class.forName("org.eclipse.ui.IAggregateWorkingSet") != null); //$NON-NLS-1$
        } catch (final Exception e) {
            /* Suppress */
        }

        if (aggregateWorkingSetAvailable && isAggregateWorkingSet(workingSet)) {
            try {
                final Class aggregateClass = Class.forName("org.eclipse.ui.IAggregateWorkingSet"); //$NON-NLS-1$
                final Method getComponentsMethod = aggregateClass.getMethod("getComponents", (Class[]) null); //$NON-NLS-1$
                final IWorkingSet[] components = (IWorkingSet[]) getComponentsMethod.invoke(workingSet,
                        (Object[]) null);

                for (int i = 0; i < components.length; i++) {
                    addToWorkingSet(project, components[i]);
                }

                return;
            } catch (final Throwable t) {
                final String messageFormat = "Could not add {0} to working set {1}"; //$NON-NLS-1$
                final String message = MessageFormat.format(messageFormat, project.getName(),
                        WorkingSetHelper.getLabel(workingSet));
                log.error(message, t);
            }
        }

        final IAdaptable[] setMembers = workingSet.getElements();
        final IAdaptable[] newMembers = new IAdaptable[setMembers.length + 1];

        System.arraycopy(setMembers, 0, newMembers, 0, setMembers.length);

        newMembers[setMembers.length] = project;

        workingSet.setElements(newMembers);
    } catch (final Exception e) {
        final String messageFormat = "Could not add {0} to working set {1}"; //$NON-NLS-1$
        final String message = MessageFormat.format(messageFormat, project.getName(), getLabel(workingSet));
        log.error(message, e);
    }
}

From source file:com.liferay.portal.test.TestUtil.java

public static void initDLAppDependencies() throws Exception {
    // Needed by the DLAApp
    WorkflowHandlerRegistryUtil.register(new DLFileEntryWorkflowHandler());
    TestUtil.initMessageBus();/*www  .j  a  v  a 2 s  .  co  m*/
    SearchEngineUtil.setIndexReadOnly(true);
    IndexerRegistryUtil.register(DLFileEntry.class.getName(), Mockito.mock(Indexer.class));

    // Have to initialize the transaction callback list, should be an easier way to do this
    Method m = TransactionCommitCallbackUtil.class.getDeclaredMethod("pushCallbackList", null);
    m.setAccessible(true);
    m.invoke(null, null);
}

From source file:io.github.pellse.decorator.util.reflection.ReflectionUtils.java

public static Object invoke(Object obj, Method method, Object... args) {
    return CheckedSupplier.of(() -> {
        method.setAccessible(true);//from w  w w  . ja  v a 2 s  .  c  om
        return method.invoke(obj, args);
    }).get();
}

From source file:Main.java

/**
 * Returns a clone of the specified object, if it can be cloned, otherwise
 * throws a CloneNotSupportedException./* w  w  w . ja  v a2s. co m*/
 * 
 * @param object
 *          the object to clone (<code>null</code> not permitted).
 * @return A clone of the specified object.
 * @throws CloneNotSupportedException
 *           if the object cannot be cloned.
 */
public static Object clone(final Object object) throws CloneNotSupportedException {
    if (object == null) {
        throw new IllegalArgumentException("Null 'object' argument.");
    }

    try {
        final Method method = object.getClass().getMethod("clone", (Class[]) null);
        if (Modifier.isPublic(method.getModifiers())) {
            return method.invoke(object, (Object[]) null);
        }
    } catch (NoSuchMethodException e) {
        System.out.println("Object without clone() method is impossible.");
    } catch (IllegalAccessException e) {
        System.out.println("Object.clone(): unable to call method.");
    } catch (InvocationTargetException e) {
        System.out.println("Object without clone() method is impossible.");
    }

    throw new CloneNotSupportedException("Failed to clone.");
}

From source file:Main.java

public static void setGL16Mode() {
    System.err.println("Orion::setGL16Mode");
    try {/*from  w ww.  j  ava 2s .c  o  m*/
        if (successful) {
            Constructor RegionParamsConstructor = epdControllerRegionParamsClass.getConstructor(new Class[] {
                    Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, epdControllerWaveClass });

            Object localRegionParams = RegionParamsConstructor
                    .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[1] }); // Wave = GU

            Method epdControllerSetRegionMethod = epdControllerClass.getMethod("setRegion",
                    new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass,
                            epdControllerModeClass });
            epdControllerSetRegionMethod.invoke(null,
                    new Object[] { "Orion", regionEnums[2], localRegionParams, modeEnums[2] }); // Mode = ONESHOT_ALL
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jdal.aop.DeclareMixinAdvisor.java

/**
 * Create a DelegateFactory using the aspect and factory method
 * @param method factory method/*  w ww.  j  a v  a 2 s.  co m*/
 * @param aspect aspect instance
 * @return a new delegate factory
 */
private static DelegateFactoryIntroductionInterceptor createAspect(final Method method, final Object aspect) {
    DelegateFactory delegateFactory = new DelegateFactory() {

        @Override
        public Object createNewDelegate(Object targetObject) throws Exception {
            return method.invoke(aspect, targetObject);

        }
    };

    return new DelegateFactoryIntroductionInterceptor(delegateFactory, method.getReturnType());
}

From source file:com.maverick.http.SocketWithLayeredTransport.java

public static String getExceptionMessageChain(Throwable t) {
    StringBuffer buf = new StringBuffer();
    while (t != null) {
        if (buf.length() > 0 && !buf.toString().endsWith(".")) { //$NON-NLS-1$
            buf.append(". "); //$NON-NLS-1$
        }// w w  w .  j a va 2  s .  c  om
        if (t.getMessage() != null) {
            buf.append(t.getMessage().trim());
        }
        try {
            Method m = t.getClass().getMethod("getCause", (Class[]) null); //$NON-NLS-1$
            t = (Throwable) m.invoke(t, (Object[]) null);
        } catch (Throwable ex) {
        }
    }
    return buf.toString();
}