Java Code Examples for java.lang.reflect.Method.invoke()

The following are Jave code examples for showing how to use invoke() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: goku-jdbc   File: GokuInvocationHandler.java   View Source Code Vote up 7 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        Object ret = method.invoke(orig, args);
        Class<?> returnType = method.getReturnType();
        if (WRAP_TARGET_CLASSES.contains(returnType)) {
            ret = Proxy.newProxyInstance(returnType.getClassLoader(), new Class[]{returnType},
                    new GokuInvocationHandler(ret));
        }
        return ret;
    } catch (InvocationTargetException ex) {
        Throwable targetEx = ex.getTargetException();
        if (targetEx instanceof SQLException) {
            targetEx = new GokuSQLException((SQLException) targetEx);
        }
        throw targetEx;
    }
}
 
Example 2
Project: Halloween   File: ReflectionUtils.java   View Source Code Vote up 6 votes
/**
 * Invoke Method methodToAccess on an Object instance.
 */
public static final <T, E> T invokeMethod(final Method methodToAccess, E instance, Object... args)
{
	try
	{
		if (methodToAccess.getReturnType().equals(Void.TYPE))
		{
			methodToAccess.invoke(instance, args);
			return null;
		}
		else
		{
			return (T)methodToAccess.invoke(instance, args);
		}
	}
	catch (Exception ex)
	{
		throw new UnableToInvokeMethodException(methodToAccess, ex);
	}
}
 
Example 3
Project: FirefoxData-android   File: CloseableHttpResponseProxy.java   View Source Code Vote up 6 votes
public Object invoke(
        final Object proxy, final Method method, final Object[] args) throws Throwable {
    final String mname = method.getName();
    if (mname.equals("close")) {
        close();
        return null;
    } else {
        try {
            return method.invoke(original, args);
        } catch (final InvocationTargetException ex) {
            final Throwable cause = ex.getCause();
            if (cause != null) {
                throw cause;
            } else {
                throw ex;
            }
        }
    }
}
 
Example 4
Project: OMGPI   File: OMGPlayer.java   View Source Code Vote up 6 votes
/**
 * Play effect of player getting damaged for all players.
 */
@SuppressWarnings("all")
public void play_damageEffect() {
    Class craftPlayer = ReflectionUtils.getClazz(ReflectionUtils.cbclasses, "CraftPlayer");
    Class entityPlayer = ReflectionUtils.getClazz(ReflectionUtils.nmsclasses, "EntityPlayer");
    Class playerConnection = ReflectionUtils.getClazz(ReflectionUtils.nmsclasses, "PlayerConnection");
    Class packet = ReflectionUtils.getClazz(ReflectionUtils.nmsclasses, "PacketPlayOutEntityStatus");
    for (Player p1 : Bukkit.getOnlinePlayers()) {
        try {
            Object nmsPlayer = craftPlayer.getDeclaredMethod("getHandle").invoke(craftPlayer.cast(p1));
            Object conn = entityPlayer.getDeclaredField("playerConnection").get(nmsPlayer);
            Method sendPacket = playerConnection.getDeclaredMethod("sendPacket", ReflectionUtils.getClazz(ReflectionUtils.nmsclasses, "Packet"));
            sendPacket.invoke(conn, packet.getConstructor(entityPlayer, byte.class).newInstance(craftPlayer.getDeclaredMethod("getHandle").invoke(craftPlayer.cast(bukkit)), (byte) 2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 5
Project: oscm   File: InitializerTest.java   View Source Code Vote up 6 votes
@Test
public void testLoggingWrongFileType() throws Exception {
    File log4jFile = createLog4jFile(LOG4J_CONFIG1);
    try {
        // Set path of log4j properties
        String log4jPath = log4jFile.getCanonicalPath();
        setSysSetting(log4jPath);

        // Invoke "private" method :)
        Method method = testElm.getClass().getDeclaredMethod(
                "postConstruct");
        method.setAccessible(true);
        method.invoke(testElm);

    } finally {
        log4jFile.delete();
        resetSysSetting();
    }

}
 
Example 6
Project: JAVA-   File: Request2ModelUtil.java   View Source Code Vote up 6 votes
/**
 * 根据传递的参数修改数据
 * 
 * @param o
 * @param parameterMap
 */
public static final void covertObj(Object o, Map<String, String[]> parameterMap) {
	Class<?> clazz = o.getClass();
	Iterator<Map.Entry<String, String[]>> iterator = parameterMap.entrySet().iterator();
	while (iterator.hasNext()) {
		Map.Entry<String, String[]> entry = iterator.next();
		String key = entry.getKey().trim();
		String value = entry.getValue()[0].trim();
		try {
			Method method = setMethod(key, clazz);
			if (method != null) {
				Class<?>[] parameterTypes = method.getParameterTypes();
				if (method != null) {
					Object[] param_value = new Object[] { TypeParseUtil.convert(value, parameterTypes[0], null) };
					method.invoke(o, param_value);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
 
Example 7
Project: BaseClient   File: Reflector.java   View Source Code Vote up 6 votes
public static Object call(ReflectorMethod p_call_0_, Object... p_call_1_)
{
    try
    {
        Method method = p_call_0_.getTargetMethod();

        if (method == null)
        {
            return null;
        }
        else
        {
            Object object = method.invoke((Object)null, p_call_1_);
            return object;
        }
    }
    catch (Throwable throwable)
    {
        handleException(throwable, (Object)null, p_call_0_, p_call_1_);
        return null;
    }
}
 
Example 8
Project: scanning   File: Bean.java   View Source Code Vote up 6 votes
/**
    * Method reflects the fields into the map of field values.
    * @param theBean
    * @throws NoSuchMethodException
    * @throws SecurityException
    * @throws IllegalAccessException
    * @throws IllegalArgumentException
    * @throws InvocationTargetException
    */
private void init(Object theBean) throws Exception {

	Collection<FieldValue> fields = FieldUtils.getModelFields(theBean);
	for (FieldValue field : fields) {
		String fieldName = field.getName();
		try {
			String getterName = getGetterName(fieldName);
			Method getter     = theBean.getClass().getMethod(getterName);
			Object value      = getter.invoke(theBean);
			if (value!=null) {
				data.put(fieldName, value);
			}
		} catch (NoSuchMethodException nsme) {
			continue; // It is legal to have a field with no getter value.
		}
	}
}
 
Example 9
Project: springbootWeb   File: MapConverter.java   View Source Code Vote up 6 votes
/**
 * 将一个 JavaBean 对象转化为一个  Map
 *
 * @param bean 要转化的JavaBean 对象
 * @return 转化出来的  Map 对象
 */
public static Map<String, Object> toMap(Object bean) {
    Map<String, Object> returnMap = null;
    try {
        Class<?> type = bean.getClass();
        returnMap = new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, null);
                }
            }
        }
    } catch (Exception e) {
        returnMap = null;
        logger.error(ExceptionUtil.parseException(e));
    }
    return returnMap;
}
 
Example 10
Project: TPlayer   File: MethodProxies.java   View Source Code Vote up 6 votes
@Override
public Object call(Object who, Method method, Object... args) throws Throwable {
    boolean slice = ParceledListSliceCompat.isReturnParceledListSlice(method);
    int userId = VUserHandle.myUserId();
    List<ResolveInfo> appResult = VPackageManager.get().queryIntentContentProviders((Intent) args[0], (String) args[1],
            (Integer) args[2], userId);
    Object _hostResult = method.invoke(who, args);
    List<ResolveInfo> hostResult = slice ? ParceledListSlice.getList.call(_hostResult)
            : (List) _hostResult;
    if (hostResult != null) {
        Iterator<ResolveInfo> iterator = hostResult.iterator();
        while (iterator.hasNext()) {
            ResolveInfo info = iterator.next();
            if (info == null || info.providerInfo == null || !isVisiblePackage(info.providerInfo.applicationInfo)) {
                iterator.remove();
            }
        }
        appResult.addAll(hostResult);
    }
    if (ParceledListSliceCompat.isReturnParceledListSlice(method)) {
        return ParceledListSliceCompat.create(appResult);
    }
    return appResult;
}
 
Example 11
Project: helper   File: HelperEventListener.java   View Source Code Vote up 5 votes
@SuppressWarnings("JavaReflectionMemberAccess")
private static void unregisterListener(Class<? extends Event> eventClass, Listener listener) {
    try {
        // unfortunately we can't cache this reflect call, as the method is static
        Method getHandlerListMethod = eventClass.getMethod("getHandlerList");
        HandlerList handlerList = (HandlerList) getHandlerListMethod.invoke(null);
        handlerList.unregister(listener);
    } catch (Throwable t) {
        // ignored
    }
}
 
Example 12
Project: Android-skin-support   File: SkinCompatManager.java   View Source Code Vote up 5 votes
/**
 * 获取皮肤包资源{@link Resources}.
 *
 * @param skinPkgPath sdcard中皮肤包路径.
 * @return
 */
@Nullable
public Resources getSkinResources(String skinPkgPath) {
    try {
        AssetManager assetManager = AssetManager.class.newInstance();
        Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
        addAssetPath.invoke(assetManager, skinPkgPath);

        Resources superRes = mAppContext.getResources();
        return new Resources(assetManager, superRes.getDisplayMetrics(), superRes.getConfiguration());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 13
Project: jvm-sandbox   File: SandboxReflectUtils.java   View Source Code Vote up 5 votes
public static <T> T unCaughtInvokeMethod(final Method method,
                                         final Object target,
                                         final Object... parameterArray) {
    final boolean isAccessible = method.isAccessible();
    try {
        method.setAccessible(true);
        return (T) method.invoke(target, parameterArray);
    } catch (Throwable e) {
        throw new UnCaughtException(e);
    } finally {
        method.setAccessible(isAccessible);
    }
}
 
Example 14
Project: mobly-bundled-snippets   File: AudioSnippet.java   View Source Code Vote up 5 votes
@Rpc(description = "Silences all audio streams.")
public void muteAll() throws Exception {
    /* Get numStreams from AudioSystem through reflection. If for some reason this fails,
     * calling muteAll will throw. */
    Class<?> audioSystem = Class.forName("android.media.AudioSystem");
    Method getNumStreamTypes = audioSystem.getDeclaredMethod("getNumStreamTypes");
    int numStreams = (int) getNumStreamTypes.invoke(null /* instance */);
    for (int i = 0; i < numStreams; i++) {
        mAudioManager.setStreamVolume(i /* audio stream */, 0 /* value */, 0 /* flags */);
    }
}
 
Example 15
Project: incubator-netbeans   File: IndexerCache.java   View Source Code Vote up 5 votes
public C() {
    Map<String, Integer> order = null;
    Method getMIMETypesMethod = null;
    try {
        getMIMETypesMethod = MIMEResolver.class.getDeclaredMethod("getMIMETypes"); //NOI18N
    } catch (Exception ex) {
        // ignore
    }

    if (getMIMETypesMethod != null) {
        Collection<? extends MIMEResolver> resolvers = Lookup.getDefault().lookupAll(MIMEResolver.class);
        order = new HashMap<String, Integer>();
        int idx = 0;
        for(MIMEResolver r : resolvers) {
            String [] mimeTypes = null;
            try {
                mimeTypes = (String []) getMIMETypesMethod.invoke(r);
            } catch (Exception e) {
                // ignore;
            }

            if (mimeTypes != null) {
                for(String mimeType : mimeTypes) {
                    order.put(mimeType, idx);
                }
            }

            idx++;
        }
    }

    orderByResolvers = order != null && order.size() > 0 ? order : null;
}
 
Example 16
Project: openjdk-jdk10   File: ClientId.java   View Source Code Vote up 5 votes
ClientId(int version, String hostname, int port, String protocol,
        Control[] bindCtls, OutputStream trace, String socketFactory) {
    this.version = version;
    this.hostname = hostname.toLowerCase(Locale.ENGLISH);  // ignore case
    this.port = port;
    this.protocol = protocol;
    this.bindCtls = (bindCtls != null ? bindCtls.clone() : null);
    this.trace = trace;
    //
    // Needed for custom socket factory pooling
    //
    this.socketFactory = socketFactory;
    if ((socketFactory != null) &&
         !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
        try {
            Class<?> socketFactoryClass =
                    Obj.helper.loadClass(socketFactory);
            this.sockComparator = socketFactoryClass.getMethod(
                            "compare", new Class<?>[]{Object.class, Object.class});
            Method getDefault = socketFactoryClass.getMethod(
                                        "getDefault", new Class<?>[]{});
            this.factory =
                    (SocketFactory)getDefault.invoke(null, new Object[]{});
        } catch (Exception e) {
            // Ignore it here, the same exceptions are/will be handled by
            // LdapPoolManager and Connection classes.
            if (debug) {
                System.out.println("ClientId received an exception");
                e.printStackTrace();
            }
        }
    } else {
         isDefaultSockFactory = true;
    }

    // The SocketFactory field is not used in the myHash
    // computation as there is no right way to compute the hash code
    // for this field. There is no harm in skipping it from the hash
    // computation
    myHash = version + port
        + (trace != null ? trace.hashCode() : 0)
        + (this.hostname != null ? this.hostname.hashCode() : 0)
        + (protocol != null ? protocol.hashCode() : 0)
        + (ctlHash=hashCodeControls(bindCtls));
}
 
Example 17
Project: TPlayer   File: SearchManagerStub.java   View Source Code Vote up 5 votes
@Override
public Object call(Object who, Method method, Object... args) throws Throwable {
    ComponentName component = (ComponentName) args[0];
    if (component != null) {
        ActivityInfo activityInfo = VirtualCore.getPM().getActivityInfo(component, 0);
        if (activityInfo != null) {
            return null;
        }
    }
    return method.invoke(who, args);
}
 
Example 18
Project: lams   File: LocalSessionFactoryBuilder.java   View Source Code Vote up 5 votes
@Override
public Settings buildSettings(Properties props, ServiceRegistry serviceRegistry) throws HibernateException {
	Settings settings = super.buildSettings(props, serviceRegistry);
	if (this.cacheRegionFactory != null) {
		try {
			Method setRegionFactory = Settings.class.getDeclaredMethod("setRegionFactory", RegionFactory.class);
			setRegionFactory.setAccessible(true);
			setRegionFactory.invoke(settings, this.cacheRegionFactory);
		}
		catch (Exception ex) {
			throw new IllegalStateException("Failed to invoke Hibernate's setRegionFactory method", ex);
		}
	}
	return settings;
}
 
Example 19
Project: openjdk-jdk10   File: MethodUtil.java   View Source Code Vote up 5 votes
private static Object invoke(Method m, Object obj, Object[] params)
    throws InvocationTargetException, IllegalAccessException
{
    ensureInvocableMethod(m);
    return m.invoke(obj, params);
}
 
Example 20
Project: AstralEdit   File: Metrics.java   View Source Code Vote up 4 votes
/**
 * Gets the server specific data.
 *
 * @return The server specific data.
 */
private JSONObject getServerData() {
    // Minecraft specific data
    int playerAmount;
    try {
        // Around MC 1.8 the return type was changed to a collection from an array,
        // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
        final Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
        playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
                ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
                : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
    } catch (final Exception e) {
        playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
    }
    final int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
    String bukkitVersion = Bukkit.getVersion();
    bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);

    // OS/Java specific data
    final String javaVersion = System.getProperty("java.version");
    final String osName = System.getProperty("os.name");
    final String osArch = System.getProperty("os.arch");
    final String osVersion = System.getProperty("os.version");
    final int coreCount = Runtime.getRuntime().availableProcessors();

    final JSONObject data = new JSONObject();

    data.put("serverUUID", serverUUID);

    data.put("playerAmount", playerAmount);
    data.put("onlineMode", onlineMode);
    data.put("bukkitVersion", bukkitVersion);

    data.put("javaVersion", javaVersion);
    data.put("osName", osName);
    data.put("osArch", osArch);
    data.put("osVersion", osVersion);
    data.put("coreCount", coreCount);

    return data;
}