Example usage for java.lang Class forName

List of usage examples for java.lang Class forName

Introduction

In this page you can find the example usage for java.lang Class forName.

Prototype

@CallerSensitive
public static Class<?> forName(String className) throws ClassNotFoundException 

Source Link

Document

Returns the Class object associated with the class or interface with the given string name.

Usage

From source file:org.jasig.portlet.data.Exporter.java

public static void main(String[] args) throws Exception {
    String dir = args[0];// ww  w  .  j a  va2 s .  co  m
    String importExportContext = args[1];
    String sessionFactoryBeanName = args[2];
    String modelClassName = args[3];
    String serviceBeanName = args[4];
    String serviceBeanMethodName = args[5];

    ApplicationContext context = PortletApplicationContextLocator.getApplicationContext(importExportContext);
    SessionFactory sessionFactory = context.getBean(sessionFactoryBeanName, SessionFactory.class);
    Class<?> modelClass = Class.forName(modelClassName);

    Object service = context.getBean(serviceBeanName);
    Session session = sessionFactory.getCurrentSession();
    Transaction transaction = session.beginTransaction();

    JAXBContext jc = JAXBContext.newInstance(modelClass);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Method method = service.getClass().getMethod(serviceBeanMethodName);
    List<?> objects = (List<?>) method.invoke(service, null);

    for (Object o : objects) {
        session.lock(o, LockMode.NONE);
        JAXBElement je2 = new JAXBElement(new QName(modelClass.getSimpleName().toLowerCase()), modelClass, o);
        String output = dir + File.separator + UUID.randomUUID().toString() + ".xml";
        try {
            marshaller.marshal(je2, new FileOutputStream(output));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    transaction.commit();
}

From source file:MethodSpy.java

public static void main(String... args) {
    try {/*  www  .  java2 s .c o m*/
        Class<?> c = Class.forName(args[0]);
        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
            if (!m.getName().equals(args[1])) {
                continue;
            }
            out.format("%s%n", m.toGenericString());

            out.format(fmt, "ReturnType", m.getReturnType());
            out.format(fmt, "GenericReturnType", m.getGenericReturnType());

            Class<?>[] pType = m.getParameterTypes();
            Type[] gpType = m.getGenericParameterTypes();
            for (int i = 0; i < pType.length; i++) {
                out.format(fmt, "ParameterType", pType[i]);
                out.format(fmt, "GenericParameterType", gpType[i]);
            }

        }

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

From source file:Main.java

public static void main(String... args) {
    try {//from w ww .  j  av a  2 s.c  o  m
        Class<?> c = Class.forName(args[0]);
        out.format("Class:%n  %s%n%n", c.getCanonicalName());
        out.format("Modifiers:%n  %s%n%n", Modifier.toString(c.getModifiers()));

        out.format("Type Parameters:%n");
        TypeVariable[] tv = c.getTypeParameters();
        if (tv.length != 0) {
            out.format("  ");
            for (TypeVariable t : tv)
                out.format("%s ", t.getName());
            out.format("%n%n");
        } else {
            out.format("  -- No Type Parameters --%n%n");
        }

        out.format("Implemented Interfaces:%n");
        Type[] intfs = c.getGenericInterfaces();
        if (intfs.length != 0) {
            for (Type intf : intfs)
                out.format("  %s%n", intf.toString());
            out.format("%n");
        } else {
            out.format("  -- No Implemented Interfaces --%n%n");
        }

        out.format("Inheritance Path:%n");
        List<Class> l = new ArrayList<Class>();
        printAncestor(c, l);
        if (l.size() != 0) {
            for (Class<?> cl : l)
                out.format("  %s%n", cl.getCanonicalName());
            out.format("%n");
        } else {
            out.format("  -- No Super Classes --%n%n");
        }

        out.format("Annotations:%n");
        Annotation[] ann = c.getAnnotations();
        if (ann.length != 0) {
            for (Annotation a : ann)
                out.format("  %s%n", a.toString());
            out.format("%n");
        } else {
            out.format("  -- No Annotations --%n%n");
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:jetbrains.exodus.util.ForkedProcessRunner.java

@SuppressWarnings({ "HardcodedFileSeparator" })
public static void main(String[] args) throws Exception {
    log.info("Process started. Arguments: " + Arrays.toString(args));
    if (args.length < 2) {
        exit("Arguments do not contain port number and/or class to be run. Exit.", null);
    }//w ww.j a  v  a 2s.c om
    try {
        int port = Integer.parseInt(args[0]);
        socket = new Socket("localhost", port);
        streamer = new Streamer(socket);
    } catch (NumberFormatException e) {
        exit("Failed to parse port number: " + args[0] + ". Exit.", null);
    }
    ForkedLogic forkedLogic = null;
    try {
        Class<?> clazz = Class.forName(args[1]);
        forkedLogic = (ForkedLogic) clazz.getConstructor().newInstance();
    } catch (Exception e) {
        exit("Failed to instantiate or initialize ForkedLogic descendant", e);
    }
    // lets provide the peer with our process id
    streamer.writeString(getProcessId());
    String[] realArgs = new String[args.length - 2];
    System.arraycopy(args, 2, realArgs, 0, realArgs.length);
    forkedLogic.forked(realArgs);
}

From source file:EnumSpy.java

public static void main(String... args) {
    try {//from   w  w  w . j  av  a2  s  .co  m
        Class<?> c = Class.forName(args[0]);
        if (!c.isEnum()) {
            out.format("%s is not an enum type%n", c);
            return;
        }
        out.format("Class:  %s%n", c);

        Field[] flds = c.getDeclaredFields();
        List<Field> cst = new ArrayList<Field>(); // enum constants
        List<Field> mbr = new ArrayList<Field>(); // member fields
        for (Field f : flds) {
            if (f.isEnumConstant())
                cst.add(f);
            else
                mbr.add(f);
        }
        if (!cst.isEmpty())
            print(cst, "Constant");
        if (!mbr.isEmpty())
            print(mbr, "Field");

        Constructor[] ctors = c.getDeclaredConstructors();
        for (Constructor ctor : ctors) {
            out.format(fmt, "Constructor", ctor.toGenericString(), synthetic(ctor));
        }

        Method[] mths = c.getDeclaredMethods();
        for (Method m : mths) {
            out.format(fmt, "Method", m.toGenericString(), synthetic(m));
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:com.jgoetsch.eventtrader.EventTraderSpringLauncher.java

public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Usage: " + EventTraderSpringLauncher.class.getSimpleName() + " <files>...");
        System.out.println("       files - List of paths to spring bean definition xml files.");
        System.out.println("               Each object defined that implements Runnable will be executed");
        System.out.println("               in its own thread.");
    } else {/*w  ww  .  j a v  a 2s. co m*/
        AbstractApplicationContext context = new ClassPathXmlApplicationContext(args);

        // auto register growl notifications after all GrowlNotification objects have been instantiated
        // if it is found on the classpath
        try {
            Class.forName("com.jgoetsch.eventtrader.processor.GrowlNotification").getMethod("autoRegister")
                    .invoke(null);
        } catch (Exception e) {
            log.warn("Growl not found, cannot autoRegister notifications: {}", e.getMessage());
        }

        Map<String, Runnable> runnables = BeanFactoryUtils.beansOfTypeIncludingAncestors(context,
                Runnable.class);
        List<Thread> threads = new ArrayList<Thread>(runnables.size());
        for (final Map.Entry<String, Runnable> runner : runnables.entrySet()) {
            final Thread th = new Thread(runner.getValue(), runner.getKey());
            threads.add(th);
            th.start();
        }

        // close spring context on JVM shutdown
        // this causes all @PreDestroy methods in the runnables to be called to allow for
        // them to shutdown gracefully
        context.registerShutdownHook();

        // wait for launched threads to finish before cleaning up beans
        for (Thread th : threads) {
            try {
                th.join();
            } catch (InterruptedException e) {
            }
        }
    }
}

From source file:com.imolinfo.offline.CrossFoldValidation.java

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

    Properties p = new Properties();
    p.load(new FileInputStream("runtime.properties"));
    GlobalVariable.getInstance().setProperties(p);
    String classificatorName = Class.forName(p.getProperty("ClassificationModel")).newInstance().toString();

    SparkConf conf = new SparkConf().setAppName("CrossFoldValidation: " + classificatorName);
    final JavaSparkContext jsc = new JavaSparkContext(conf);

    invokePipeline(jsc);//from  ww w .j  av  a  2 s.c o  m
}

From source file:TXInfo.java

public static void main(String[] a) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:MusicVideo");
    int tx = con.getMetaData().getDefaultTransactionIsolation();
    String txtxt = null;// w w w  .j  av a2  s .  c  o m
    switch (tx) {
    case Connection.TRANSACTION_NONE:
        txtxt = "TRANSACTION_NONE";
        break;
    case Connection.TRANSACTION_READ_COMMITTED:
        txtxt = "TRANSACTION_READ_COMMITTED";
        break;
    case Connection.TRANSACTION_READ_UNCOMMITTED:
        txtxt = "TRANSACTION_READ_UNCOMMITTED";
        break;
    case Connection.TRANSACTION_REPEATABLE_READ:
        txtxt = "TRANSACTION_REPEATABLE_READ";
        break;
    case Connection.TRANSACTION_SERIALIZABLE:
        txtxt = "TRANSACTION_SERIALIZABLE";
        break;
    default:
        txtxt = "UNKNOWN!!";
    }
    System.out.println(txtxt);
    con.setTransactionIsolation(tx);
    System.out.println("Done");
    con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
    System.out.println("TX is now " + con.getTransactionIsolation());
}

From source file:CompileSourceInMemory.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");
    out.println("  }");
    out.println("}");
    out.close();/*w w  w  . j  a  v  a  2s  .c o  m*/
    JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));

    }
    System.out.println("Success: " + success);

    if (success) {
        try {
            Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class }).invoke(null,
                    new Object[] { null });
        } catch (ClassNotFoundException e) {
            System.err.println("Class not found: " + e);
        } catch (NoSuchMethodException e) {
            System.err.println("No such method: " + e);
        } catch (IllegalAccessException e) {
            System.err.println("Illegal access: " + e);
        } catch (InvocationTargetException e) {
            System.err.println("Invocation target: " + e);
        }
    }
}

From source file:com.apipulse.bastion.Main.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    log.info("Bastion starting. Loading chains");
    final File dir = new File("etc/chains");

    final LinkedList<ActorRef> chains = new LinkedList<ActorRef>();
    for (File file : dir.listFiles()) {
        if (!file.getName().startsWith(".") && file.getName().endsWith(".yaml")) {
            log.info("Loading chain: " + file.getName());
            ChainConfig config = new ChainConfig(IOUtils.toString(new FileReader(file)));
            ActorRef ref = BastionActors.getInstance().initChain(config.getName(),
                    Class.forName(config.getQualifiedClass()));
            Iterator<StageConfig> iterator = config.getStages().iterator();
            while (iterator.hasNext())
                ref.tell(iterator.next(), null);
            chains.add(ref);/* www .  j  av  a2s  .c  o m*/
        }
    }
    SpringApplication app = new SpringApplication();
    HashSet<Object> objects = new HashSet<Object>();
    objects.add(ApiController.class);
    final ConfigurableApplicationContext context = app.run(ApiController.class, args);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                log.info("Bastion shutting down");
                Iterator<ActorRef> iterator = chains.iterator();
                while (iterator.hasNext())
                    iterator.next().tell(new StopMessage(), null);
                Thread.sleep(2000);
                context.stop();
                log.info("Bastion shutdown complete");
            } catch (Exception e) {
            }
        }
    });
}