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 main(String[] args) throws Exception {
    Class<?> class1 = Class.forName("Rate");
    Object obj = class1.newInstance();
    for (Method m : class1.getMethods()) {
        if (m.getName().equals("myMethod")) {
            Class<?>[] parameterTypes = m.getParameterTypes();
            System.out.println(Arrays.toString(m.getParameterTypes()));
            Object methodArgs[] = new Object[parameterTypes.length];
            for (Class<?> parameterType : parameterTypes) {
                if (parameterType == Double.TYPE) {
                    double value = 0.5;
                    methodArgs[0] = value;
                }// ww w . java2s.c o m
            }
            Rate rate = (Rate) m.invoke(obj, methodArgs);
            System.out.println(rate.getValue());
        }
    }
}

From source file:com.asprise.imaging.core.Imaging.java

public static void main(String[] args) {
    if (args == null) {
        args = new String[0];
    }/*from w w  w. j  a v  a  2s .  co m*/

    // Try UI mode if possible
    try {
        if (!(args.length > 0 && "console".equalsIgnoreCase(args[args.length - 1]))
                && !java.awt.GraphicsEnvironment.isHeadless()) {
            Class<?> cls = Class.forName("com.asprise.imaging.scan.ui.workbench.demo.FrameScanDemo");
            Method meth = cls.getMethod("main", String[].class);
            String[] params = null; // init params accordingly
            meth.invoke(null, (Object) args); // static method doesn't have an instance
            return;
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }

    String copyright = "Copyright Asprise, " + Calendar.getInstance().get(Calendar.YEAR)
            + ". All Rights Reserved. Visit www.asprise.com";
    String version = "Library version: " + getLibraryVersion();

    try {
        JOptionPane.showMessageDialog(null, version, copyright,
                JOptionPane.OK_OPTION | JOptionPane.INFORMATION_MESSAGE);
    } catch (Throwable t) {
        // ignore exception
    }

    System.out.println(copyright);
    System.out.println(version);
    System.out.println(Utils.getEnvInfo(false));
}

From source file:Deet.java

public static void main(String... args) {
    if (args.length != 4) {
        err.format("Usage: java Deet <classname> <langauge> <country> <variant>%n");
        return;//w  ww .  j a va  2  s.c o  m
    }

    try {
        Class<?> c = Class.forName(args[0]);
        Object t = c.newInstance();

        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
            String mname = m.getName();
            if (!mname.startsWith("test") || (m.getGenericReturnType() != boolean.class)) {
                continue;
            }
            Type[] pType = m.getGenericParameterTypes();
            if ((pType.length != 1) || Locale.class.isAssignableFrom(pType[0].getClass())) {
                continue;
            }

            out.format("invoking %s()%n", mname);
            try {
                m.setAccessible(true);
                Object o = m.invoke(t, new Locale(args[1], args[2], args[3]));
                out.format("%s() returned %b%n", mname, (Boolean) o);

                // Handle any exceptions thrown by method to be invoked.
            } catch (InvocationTargetException x) {
                Throwable cause = x.getCause();
                err.format("invocation of %s failed: %s%n", mname, cause.getMessage());
            }
        }

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (InstantiationException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:com.alkacon.opencms.registration.CmsRegistrationFormHandler.java

/**
 * As test case.<p>//w  w  w  . j a  v  a  2s  .  c  o m
 * 
 * @param args not used
 */
public static void main(String[] args) {

    CmsUser user = new CmsUser(null, "/mylongouname/m.moossen@alkacon.com", "", "", "", "", 0, 0, 0, null);
    String code = getActivationCode(user);
    System.out.println(code);
    System.out.println(getUserName(code));

    CmsMacroResolver macroResolver = CmsMacroResolver.newInstance();
    macroResolver.setKeepEmptyMacros(true);
    // create macros for getters 
    Method[] methods = CmsUser.class.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.getReturnType() != String.class) {
            continue;
        }
        if (method.getParameterTypes().length > 0) {
            continue;
        }
        if (!method.getName().startsWith("get") || (method.getName().length() < 4)
                || method.getName().equals("getPassword")) {
            continue;
        }
        String label = ("" + method.getName().charAt(3)).toLowerCase();
        if (method.getName().length() > 4) {
            label += method.getName().substring(4);
        }
        try {
            Object value = method.invoke(user, new Object[] {});
            if (value == null) {
                value = "";
            }
            macroResolver.addMacro(label, value.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // add addinfo values as macros
    Iterator itFields = user.getAdditionalInfo().entrySet().iterator();
    while (itFields.hasNext()) {
        Map.Entry entry = (Map.Entry) itFields.next();
        if ((entry.getValue() instanceof String) && (entry.getKey() instanceof String)) {
            macroResolver.addMacro(entry.getKey().toString(), entry.getValue().toString());
        }
    }
    // add login
    macroResolver.addMacro(FIELD_LOGIN, user.getSimpleName());

}

From source file:com.ikanow.aleph2.analytics.spark.assets.SparkScalaInterpreterTopology.java

public static void main(String[] args)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {

    final SetOnce<IBucketLogger> logger = new SetOnce<>();

    try {//from   w  ww. j ava2s .  c  o m
        final Tuple2<IAnalyticsContext, Optional<ProcessingTestSpecBean>> aleph2_tuple = SparkTechnologyUtils
                .initializeAleph2(args);
        final IAnalyticsContext context = aleph2_tuple._1();
        final Optional<ProcessingTestSpecBean> test_spec = aleph2_tuple._2();

        logger.set(context.getLogger(context.getBucket()));

        // Optional: make really really sure it exists after the specified timeout
        SparkTechnologyUtils.registerTestTimeout(test_spec, () -> {
            System.exit(0);
        });

        //INFO:
        System.out.println("Starting SparkScalaInterpreterTopology logging=" + logger.optional().isPresent());

        logger.optional().ifPresent(l -> {
            l.inefficientLog(Level.INFO,
                    ErrorUtils.buildSuccessMessage("SparkScalaInterpreterTopology", "main",
                            "Starting SparkScalaInterpreterTopology.{0}",
                            Optionals.of(() -> context.getJob().get().name()).orElse("no_name")));
        });

        final SparkTopologyConfigBean job_config = BeanTemplateUtils
                .from(context.getJob().map(job -> job.config()).orElse(Collections.emptyMap()),
                        SparkTopologyConfigBean.class)
                .get();
        final String scala_script = Optional.ofNullable(job_config.script()).orElse("");

        final String wrapper_script = IOUtils.toString(
                SparkScalaInterpreterTopology.class.getClassLoader().getResourceAsStream("ScriptRunner.scala"),
                "UTF-8");
        final String to_compile = wrapper_script.replace("USER_SCRIPT", scala_script);
        final SparkCompilerService scs = new SparkCompilerService();
        final Tuple2<ClassLoader, Object> o = scs.buildClass(to_compile, "ScriptRunner", logger.optional());

        Thread.currentThread().setContextClassLoader(o._1());

        test_spec.ifPresent(spec -> System.out
                .println("OPTIONS: test_spec = " + BeanTemplateUtils.toJson(spec).toString()));

        SparkConf spark_context = new SparkConf().setAppName("SparkPassthroughTopology");

        final long streaming_batch_interval = (long) spark_context
                .getInt(SparkTopologyConfigBean.STREAMING_BATCH_INTERVAL, 10);

        // MAIN PROCESSING

        final Method m = o._2().getClass().getMethod("runScript", SparkScriptEngine.class);

        //DEBUG
        //final boolean test_mode = test_spec.isPresent(); // (serializable thing i can pass into the map)

        boolean is_streaming = context.getJob().map(j -> j.analytic_type())
                .map(t -> MasterEnrichmentType.streaming == t).orElse(false);
        final Either<JavaSparkContext, JavaStreamingContext> jsc = Lambdas.get(() -> {
            return is_streaming
                    ? Either.<JavaSparkContext, JavaStreamingContext>right(new JavaStreamingContext(
                            spark_context, Durations.seconds(streaming_batch_interval)))
                    : Either.<JavaSparkContext, JavaStreamingContext>left(new JavaSparkContext(spark_context));
        });
        try {
            final JavaSparkContext jsc_batch = jsc.either(l -> l, r -> r.sparkContext());

            final Multimap<String, JavaPairRDD<Object, Tuple2<Long, IBatchRecord>>> inputs = SparkTechnologyUtils
                    .buildBatchSparkInputs(context, test_spec, jsc_batch, Collections.emptySet());

            final Multimap<String, JavaPairDStream<String, Tuple2<Long, IBatchRecord>>> streaming_inputs = jsc
                    .<Multimap<String, JavaPairDStream<String, Tuple2<Long, IBatchRecord>>>>either(
                            l -> HashMultimap
                                    .<String, JavaPairDStream<String, Tuple2<Long, IBatchRecord>>>create(),
                            r -> SparkTechnologyUtils.buildStreamingSparkInputs(context, test_spec, r,
                                    Collections.emptySet()));

            final SparkScriptEngine script_engine_bridge = new SparkScriptEngine(context, inputs,
                    streaming_inputs, test_spec, jsc_batch, jsc.either(l -> null, r -> r), job_config);

            // Add driver and generated JARs to path:
            jsc_batch.addJar(LiveInjector.findPathJar(o._2().getClass()));

            m.invoke(o._2(), script_engine_bridge);

            jsc.either(l -> {
                l.stop();
                return null;
            }, r -> {
                r.stop();
                return null;
            });

            logger.optional().ifPresent(l -> {
                l.inefficientLog(Level.INFO,
                        ErrorUtils.buildSuccessMessage("SparkScalaInterpreterTopology", "main",
                                "Stopping SparkScalaInterpreterTopology.{0}",
                                Optionals.of(() -> context.getJob().get().name()).orElse("no_name")));
            });

            //INFO:
            System.out.println("Finished interpreter");
        } finally {
            jsc.either(l -> {
                l.close();
                return null;
            }, r -> {
                r.close();
                return null;
            });
        }
        logger.optional().ifPresent(Lambdas.wrap_consumer_u(l -> l.flush().get(10, TimeUnit.SECONDS)));
    } catch (Throwable t) {
        logger.optional().ifPresent(l -> {
            l.inefficientLog(Level.ERROR, ErrorUtils.buildSuccessMessage("SparkScalaInterpreterTopology",
                    "main",
                    ErrorUtils.getLongForm("Error executing SparkScalaInterpreterTopology.unknown: {0}", t)));
        });

        System.out.println(ErrorUtils.getLongForm("ERROR: {0}", t));
        logger.optional().ifPresent(Lambdas.wrap_consumer_u(l -> l.flush().get(10, TimeUnit.SECONDS)));
        System.exit(-1);
    }
}

From source file:Main.java

public static Object invokeMethod(Object receiver, Method method, Object... args) {
    try {/*w ww.  j a v  a 2 s .  c om*/
        return method.invoke(receiver, args);
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static void setter(Object obj, String att, Object value, Class<?> type) {
    try {//w  w  w .  ja  va  2  s.c  om
        Method method = obj.getClass().getMethod("set" + att, type);
        method.invoke(obj, value);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String getProp(String prop) {
    try {/*  w ww .j a v  a  2 s .  c om*/
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method m = c.getMethod("get", String.class);
        return (String) m.invoke(null, prop);
    } catch (Throwable e) {
        return "";
    }
}

From source file:Main.java

private static Object invokeMethod(Object object, String methodName, Object[] params, Class... types)
        throws Exception {
    Object out = null;//from   w  ww .  jav  a2  s.co  m
    Class c = object instanceof Class ? (Class) object : object.getClass();
    if (types != null) {
        Method method = c.getMethod(methodName, types);
        out = method.invoke(object, params);
    } else {
        Method method = c.getMethod(methodName);
        out = method.invoke(object);
    }
    //System.out.println(object.getClass().getName() + "." + methodName + "() = "+ out);
    return out;
}

From source file:Main.java

public static String getProp(String prop) {
    String output = "";
    try {//from  w w  w.  j av a2 s  . com
        Class<?> sp = Class.forName("android.os.SystemProperties");
        Method get = sp.getMethod("get", String.class);
        output = (String) get.invoke(null, prop);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return output;
}