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

The following examples show how to use java.lang.reflect.Method#invoke() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoginTestBean.java    From redkale with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    LoginTestBean bean = new LoginTestBean();
    bean.setSessionid("xxx"); 
    bean.setSid(23333); 
    BiFunction<DataSource, Class, List> fullloader = (s, z) -> new ArrayList();
    Method method = EntityInfo.class.getDeclaredMethod("load", Class.class, boolean.class, Properties.class,
        DataSource.class, BiFunction.class);
    method.setAccessible(true);
    final EntityInfo<CacheTestBean> info = (EntityInfo<CacheTestBean>) method.invoke(null, CacheTestBean.class, true, new Properties(), null, fullloader);
    EntityCache<CacheTestBean> cache = new EntityCache(info, null);
    FilterNode node = FilterNodeBean.createFilterNode(bean);
    System.out.println("cache = " + cache + ", node = " + node);
    Method pre = FilterNode.class.getDeclaredMethod("createPredicate", EntityCache.class);
    pre.setAccessible(true); 
    //为null是因为CacheTestBean 没有sid和sessionid这两个字段
    System.out.println(pre.invoke(node,cache));
}
 
Example 2
Source File: ReflectionUtils.java    From Noyze with Apache License 2.0 6 votes vote down vote up
/** @return A WindowManagerGlobal instance. */
public static Object getWindowManagerGlobal() {
    if (wManagerGlobal != null)
        return wManagerGlobal;

    try {
        Class<?> mWindowManagerGlobal = Class.forName("android.view.WindowManagerGlobal");
        if (null == mWindowManagerGlobal) return null;
        Method mMethod = mWindowManagerGlobal.getDeclaredMethod("getInstance");
        if (null == mMethod) return null;
        mMethod.setAccessible(true);
        wManagerGlobal = mMethod.invoke(null);
    } catch (Throwable t) {
        LogUtils.LOGE("ReflectionUtils", "Error accessing WindowManagerGlobal.", t);
    }

    return wManagerGlobal;
}
 
Example 3
Source File: RepositoryId.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static String getIdFromHelper(Class clazz){
    try {
        Class helperClazz = Utility.loadClassForClass(clazz.getName()+"Helper", null,
                                clazz.getClassLoader(), clazz, clazz.getClassLoader());
        Method idMethod = helperClazz.getDeclaredMethod("id", kNoParamTypes);
        return (String)idMethod.invoke(null, kNoArgs);
    }
    catch(java.lang.ClassNotFoundException cnfe)
        {
            throw new org.omg.CORBA.MARSHAL(cnfe.toString());
        }
    catch(java.lang.NoSuchMethodException nsme)
        {
            throw new org.omg.CORBA.MARSHAL(nsme.toString());
        }
    catch(java.lang.reflect.InvocationTargetException ite)
        {
            throw new org.omg.CORBA.MARSHAL(ite.toString());
        }
    catch(java.lang.IllegalAccessException iae)
        {
            throw new org.omg.CORBA.MARSHAL(iae.toString());
}
}
 
Example 4
Source File: FullScreenAfterSplash.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void enableFullScreen(Window window) {
    try {
        Class<?> fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
        Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
        setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
        Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener");
        Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, (proxy, method, args) -> {
            switch (method.getName()) {
                case "windowEnteringFullScreen":
                    windowEnteringFullScreen = true;
                    break;
                case "windowEnteredFullScreen":
                    windowEnteredFullScreen = true;
                    break;
            }
            return null;
        });
        Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener);
        addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject);
    } catch (Exception e) {
        throw new RuntimeException("FullScreen utilities not available", e);
    }
}
 
Example 5
Source File: ProximityManager.java    From react-native-twilio-programmable-voice with MIT License 6 votes vote down vote up
private void initProximityWakeLock() {
    // Check if PROXIMITY_SCREEN_OFF_WAKE_LOCK is implemented, not part of public api.
    // PROXIMITY_SCREEN_OFF_WAKE_LOCK and isWakeLockLevelSupported are available from api 21
    try {
        boolean isSupported;
        int proximityScreenOffWakeLock;
        if (android.os.Build.VERSION.SDK_INT < 21) {
            Field field = PowerManager.class.getDeclaredField("PROXIMITY_SCREEN_OFF_WAKE_LOCK");
            proximityScreenOffWakeLock = (Integer) field.get(null);

            Method method = powerManager.getClass().getDeclaredMethod("getSupportedWakeLockFlags");
            int powerManagerSupportedFlags = (Integer) method.invoke(powerManager);
            isSupported = ((powerManagerSupportedFlags & proximityScreenOffWakeLock) != 0x0);
        } else {
            proximityScreenOffWakeLock = powerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK;
            isSupported = powerManager.isWakeLockLevelSupported(proximityScreenOffWakeLock);
        }
        if (isSupported) {
            proximityWakeLock = powerManager.newWakeLock(proximityScreenOffWakeLock, TAG);
            proximityWakeLock.setReferenceCounted(false);
        }
    } catch (Exception e) {
        Log.e(TAG, "Failed to get proximity screen locker.");
    }
}
 
Example 6
Source File: AbstractAwsClientWrapper.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * TODO: メソッドコメント
 * 
 * @param client
 * @return
 */
public AmazonEC2 wrap(final AmazonEC2 client) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (!AmazonWebServiceResult.class.isAssignableFrom(method.getReturnType())) {
                return method.invoke(client, args);
            }

            return doInvoke(client, proxy, method, args);
        }
    };

    return (AmazonEC2) Proxy.newProxyInstance(LoggingAwsClientWrapper.class.getClassLoader(),
            new Class[] { AmazonEC2.class }, handler);
}
 
Example 7
Source File: LaunchAppropriateUI.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Launch the appropriate UI.
 *
 * @throws java.lang.Exception
 */
public void launch() throws Exception {
    // Sanity-check the loaded BCEL classes
    if (!CheckBcel.check()) {
        System.exit(1);
    }

    int launchProperty = getLaunchProperty();

    if (GraphicsEnvironment.isHeadless() || launchProperty == TEXTUI) {
        FindBugs2.main(args);
    } else if (launchProperty == SHOW_HELP) {
        ShowHelp.main(args);
    } else if (launchProperty == SHOW_VERSION) {
        Version.main(new String[] { "-release" });
    } else {
        Class<?> launchClass = Class.forName("edu.umd.cs.findbugs.gui2.Driver");
        Method mainMethod = launchClass.getMethod("main", args.getClass());
        mainMethod.invoke(null, (Object) args);
    }

}
 
Example 8
Source File: ConnectorIOUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void closeQuietly(Object closeable) {
   try {
      if (closeable != null) {
         Method closeMethod = closeable.getClass().getMethod("close");
         closeMethod.invoke(closeable);
      }
   } catch (SecurityException var2) {
      ;
   } catch (NoSuchMethodException var3) {
      ;
   } catch (IllegalArgumentException var4) {
      ;
   } catch (IllegalAccessException var5) {
      ;
   } catch (InvocationTargetException var6) {
      ;
   }

}
 
Example 9
Source File: RollingUpgradeDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static Object createCache(Properties systemProperties)
    throws Exception {
  systemProperties.put(DistributionConfig.LOG_FILE_NAME, "rollingUpgradeCacheVM"+VM.getCurrentVMNum()+".log");
  Class aClass = Thread.currentThread().getContextClassLoader()
      .loadClass("com.gemstone.gemfire.cache.CacheFactory");
  Constructor constructor = aClass.getConstructor(Properties.class);
  Object cacheFactory = constructor.newInstance(systemProperties);

  Method createMethod = aClass.getMethod("create");
  Object cache = createMethod.invoke(cacheFactory);

  return cache;
}
 
Example 10
Source File: FluxListenerInvocationHandler.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getDeclaringClass().equals(listenerType)) {
        delegate.accept((T) args[0]);
        return null;
    }
    return method.invoke(this, args);
}
 
Example 11
Source File: KerasModelConverter.java    From wekaDeeplearning4j with GNU General Public License v3.0 5 votes vote down vote up
private static void saveH5File(File modelFile, File outputFolder) {
    try {
        INDArray testShape = Nd4j.zeros(1, 3, 224, 224);
        String modelName = modelFile.getName();
        Method method = null;
        try {
            method = InputType.class.getMethod("setDefaultCNN2DFormat", CNN2DFormat.class);
            method.invoke(null, CNN2DFormat.NCHW);
        } catch (NoSuchMethodException ex) {
            System.err.println("setDefaultCNN2DFormat() not found on InputType class... " +
                    "Are you using the custom built deeplearning4j-nn.jar?");
            System.exit(1);
        }

        if (modelName.contains("EfficientNet")) {
            // Fixes for EfficientNet family of models
            testShape = Nd4j.zeros(1, 224, 224, 3);
            method.invoke(null, CNN2DFormat.NHWC);
            // We don't want the resulting .zip files to have 'Fixed' in the name, so we'll strip it off here
            modelName = modelName.replace("Fixed", "");
        }
        ComputationGraph kerasModel = KerasModelImport.importKerasModelAndWeights(modelFile.getAbsolutePath());
        kerasModel.feedForward(testShape, false);
        // e.g. ResNet50.h5 -> KerasResNet50.zip
        modelName = "Keras" + modelName.replace(".h5", ".zip");
        String newZip = Paths.get(outputFolder.getPath(), modelName).toString();
        kerasModel.save(new File(newZip));
        System.out.println("Saved file " + newZip);
    } catch (Exception e) {
        System.err.println("\n\nCouldn't save " + modelFile.getName());
        e.printStackTrace();
    }
}
 
Example 12
Source File: NetRexxEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke a static method.
 * @param rexxclass Class to invoke the method against
 * @param method The name of the method to call.
 * @param args an array of arguments to be
 * passed to the extension, which may be either
 * Vectors of Nodes, or Strings.
 */
Object callStatic(Class rexxclass, String method, Object[] args)
throws BSFException
{
    //***** ISSUE: Currently supports only static methods
    Object retval = null;
    try
    {
        if (rexxclass != null)
        {
            //***** This should call the lookup used in BML, for typesafety
            Class[] argtypes=new Class[args.length];
            for(int i=0;i<args.length;++i)
                argtypes[i]=args[i].getClass();

            Method m=MethodUtils.getMethod(rexxclass, method, argtypes);
            retval=m.invoke(null,args);
        }
        else
        {
            logger.error("NetRexxEngine: ERROR: rexxclass==null!");
        }
    }
    catch(Exception e)
    {
        e.printStackTrace ();
        if (e instanceof InvocationTargetException)
        {
            Throwable t = ((InvocationTargetException)e).getTargetException ();
            t.printStackTrace ();
        }
        throw new BSFException (BSFException.REASON_IO_ERROR,
                                e.getMessage (),
                                e);
    }
    return retval;
}
 
Example 13
Source File: BmpEncoder.java    From pumpernickel with MIT License 5 votes vote down vote up
public static boolean isOpaque(BufferedImage bi) {
	try {
		Method m = BufferedImage.class.getMethod("getTransparency",
				new Class[] {});
		Object returnValue = m.invoke(bi, new Object[] {});
		Field f = BufferedImage.class.getField("OPAQUE");
		return f.get(null).equals(returnValue);
	} catch (Throwable e) {
		// in earlier JVMs this will be a problem:
		int type = bi.getType();
		return (type == BufferedImage.TYPE_4BYTE_ABGR
				|| type == BufferedImage.TYPE_4BYTE_ABGR_PRE
				|| type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_ARGB_PRE);
	}
}
 
Example 14
Source File: DeviceUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取基带版本 BASEBAND-VER
 * @return 基带版本 BASEBAND-VER
 */
public static String getBaseband_Ver() {
    String basebandVersion = "";
    try {
        Class clazz = Class.forName("android.os.SystemProperties");
        Object invoker = clazz.newInstance();
        Method method = clazz.getMethod("get", String.class, String.class);
        Object result = method.invoke(invoker, "gsm.version.baseband", "no message");
        basebandVersion = (String) result;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getBaseband_Ver");
    }
    return basebandVersion;
}
 
Example 15
Source File: ProtobufDecoder.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new {@code Message.Builder} instance for the given class.
 * <p>This method uses a ConcurrentHashMap for caching method lookups.
 */
private static Message.Builder getMessageBuilder(Class<?> clazz) throws Exception {
	Method method = methodCache.get(clazz);
	if (method == null) {
		method = clazz.getMethod("newBuilder");
		methodCache.put(clazz, method);
	}
	return (Message.Builder) method.invoke(clazz);
}
 
Example 16
Source File: ReflectUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static Object invoke(Object target, String methodName, Object[] args) {
    try {
        Class<? extends Object> clazz = target.getClass();
        Method method = findMethod(clazz, methodName, args);
        method.setAccessible(true);
        return method.invoke(target, args);
    } catch (Exception e) {
        throw new FlowableException("couldn't invoke " + methodName + " on " + target, e);
    }
}
 
Example 17
Source File: AutoPropertyPopulater.java    From jfixture with MIT License 5 votes vote down vote up
private void trySetProperty(Object specimen, Method method, Object propertySpecimen) {
    try {
        method.invoke(specimen, propertySpecimen);
    } catch (Exception e) {
        throw new ObjectCreationException(String.format("Error setting property %s", method.getName()), e);
    }
}
 
Example 18
Source File: WebServiceAp.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private String parseArguments() {
    // let's try to parse JavacOptions

    String classDir = null;
    try {
        ClassLoader cl = WebServiceAp.class.getClassLoader();
        Class javacProcessingEnvironmentClass = Class.forName("com.sun.tools.javac.processing.JavacProcessingEnvironment", false, cl);
        if (javacProcessingEnvironmentClass.isInstance(processingEnv)) {
            Method getContextMethod = javacProcessingEnvironmentClass.getDeclaredMethod("getContext");
            Object tmpContext = getContextMethod.invoke(processingEnv);
            Class optionsClass = Class.forName("com.sun.tools.javac.util.Options", false, cl);
            Class contextClass = Class.forName("com.sun.tools.javac.util.Context", false, cl);
            Method instanceMethod = optionsClass.getDeclaredMethod("instance", new Class[]{contextClass});
            Object tmpOptions = instanceMethod.invoke(null, tmpContext);
            if (tmpOptions != null) {
                Method getMethod = optionsClass.getDeclaredMethod("get", new Class[]{String.class});
                Object result = getMethod.invoke(tmpOptions, "-s"); // todo: we have to check for -d also
                if (result != null) {
                    classDir = (String) result;
                }
                this.options.verbose = getMethod.invoke(tmpOptions, "-verbose") != null;
            }
        }
    } catch (Exception e) {
        /// some Error was here - problems with reflection or security
        processWarning(WebserviceapMessages.WEBSERVICEAP_PARSING_JAVAC_OPTIONS_ERROR());
        report(e.getMessage());
    }

    if (classDir == null) { // some error within reflection block
        String property = System.getProperty("sun.java.command");
        if (property != null) {
            Scanner scanner = new Scanner(property);
            boolean sourceDirNext = false;
            while (scanner.hasNext()) {
                String token = scanner.next();
                if (sourceDirNext) {
                    classDir = token;
                    sourceDirNext = false;
                } else if ("-verbose".equals(token)) {
                    options.verbose = true;
                } else if ("-s".equals(token)) {
                    sourceDirNext = true;
                }
            }
        }
    }
    if (classDir != null) {
        sourceDir = new File(classDir);
    }
    return classDir;
}
 
Example 19
Source File: Endpoint.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private void addNettyBuilderProps(NettyChannelBuilder channelBuilder, Properties props)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    if (props == null) {
        return;
    }

    for (Map.Entry<?, ?> es : props.entrySet()) {
        Object methodprop = es.getKey();
        if (methodprop == null) {
            continue;
        }
        String methodprops = String.valueOf(methodprop);

        Matcher match = METHOD_PATTERN.matcher(methodprops);

        String methodName = null;

        if (match.matches() && match.groupCount() == 1) {
            methodName = match.group(1).trim();

        }
        if (null == methodName || "forAddress".equals(methodName) || "build".equals(methodName)) {

            continue;
        }

        Object parmsArrayO = es.getValue();
        Object[] parmsArray;
        if (!(parmsArrayO instanceof Object[])) {
            parmsArray = new Object[] {parmsArrayO};

        } else {
            parmsArray = (Object[]) parmsArrayO;
        }

        Class<?>[] classParms = new Class[parmsArray.length];
        int i = -1;
        for (Object oparm : parmsArray) {
            ++i;

            if (null == oparm) {
                classParms[i] = Object.class;
                continue;
            }

            Class<?> unwrapped = WRAPPERS_TO_PRIM.get(oparm.getClass());
            if (null != unwrapped) {
                classParms[i] = unwrapped;
            } else {

                Class<?> clz = oparm.getClass();

                Class<?> ecz = clz.getEnclosingClass();
                if (null != ecz && ecz.isEnum()) {
                    clz = ecz;
                }

                classParms[i] = clz;
            }
        }

        final Method method = channelBuilder.getClass().getMethod(methodName, classParms);

        method.invoke(channelBuilder, parmsArray);

        if (logger.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder(200);
            String sep = "";
            for (Object p : parmsArray) {
                sb.append(sep).append(p + "");
                sep = ", ";

            }
            logger.trace(format("Endpoint with url: %s set managed channel builder method %s (%s) ", url,
                    method, sb.toString()));

        }

    }

}
 
Example 20
Source File: FailoverConnectionProxy.java    From Komondor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public synchronized Object invokeMore(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();

    if (METHOD_SET_READ_ONLY.equals(methodName)) {
        this.explicitlyReadOnly = (Boolean) args[0];
        if (this.failoverReadOnly && connectedToSecondaryHost()) {
            return null;
        }
    }

    if (this.isClosed && !allowedOnClosedConnection(method)) {
        if (this.autoReconnect && !this.closedExplicitly) {
            this.currentHostIndex = NO_CONNECTION_INDEX; // Act as if this is the first connection but let it sync with the previous one.
            pickNewConnection();
            this.isClosed = false;
            this.closedReason = null;
        } else {
            String reason = "No operations allowed after connection closed.";
            if (this.closedReason != null) {
                reason += ("  " + this.closedReason);
            }
            throw SQLError.createSQLException(reason, SQLError.SQL_STATE_CONNECTION_NOT_OPEN, null /* no access to a interceptor here... */);
        }
    }

    Object result = null;

    try {
        result = method.invoke(this.thisAsConnection, args);
        result = proxyIfReturnTypeIsJdbcInterface(method.getReturnType(), result);
    } catch (InvocationTargetException e) {
        dealWithInvocationException(e);
    }

    if (METHOD_SET_AUTO_COMMIT.equals(methodName)) {
        this.explicitlyAutoCommit = (Boolean) args[0];
    }

    if ((this.explicitlyAutoCommit || METHOD_COMMIT.equals(methodName) || METHOD_ROLLBACK.equals(methodName)) && readyToFallBackToPrimaryHost()) {
        // Fall back to primary host at transaction boundary
        fallBackToPrimaryIfAvailable();
    }

    return result;
}