Example usage for java.lang Class newInstance

List of usage examples for java.lang Class newInstance

Introduction

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

Prototype

@CallerSensitive
@Deprecated(since = "9")
public T newInstance() throws InstantiationException, IllegalAccessException 

Source Link

Document

Creates a new instance of the class represented by this Class object.

Usage

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;//from  w  ww  .  ja v  a2s. 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:kilim.test.TaskTestClassLoader.java

public static void main(String[] args) throws Exception {
    Class<?> c = new TaskTestClassLoader(Thread.currentThread().getContextClassLoader()).loadClass(args[0],
            true);/*from w  w  w  . jav a 2 s . c o  m*/
    c.newInstance();
}

From source file:HasBatteries.java

public static void main(String[] args) {
    Class c = null;/*from  w  w w  .  j a va2 s. c o  m*/
    try {
        c = Class.forName("FancyToy");
    } catch (ClassNotFoundException e) {
        System.out.println("Can't find FancyToy");
        System.exit(1);
    }
    printInfo(c);
    Class[] faces = c.getInterfaces();
    for (int i = 0; i < faces.length; i++)
        printInfo(faces[i]);
    Class cy = c.getSuperclass();
    Object o = null;
    try {
        // Requires default constructor:
        o = cy.newInstance(); // (*1*)
    } catch (InstantiationException e) {
        System.out.println("Cannot instantiate");
        System.exit(1);
    } catch (IllegalAccessException e) {
        System.out.println("Cannot access");
        System.exit(1);
    }
    printInfo(o.getClass());

}

From source file:MainClass.java

public static void main(String args[]) {
    String name = "http://urlWithClassName";
    try {//from w ww. j  a  va  2s  .  com
        if (!name.endsWith(".class")) {
            System.err.println("That doesn't look like a byte code file!");
            return;
        }
        URL u = new URL(name);
        URLClassLoader ucl = new URLClassLoader(u);

        // parse out the name of the class from the URL
        String s = u.getFile();
        String classname = s.substring(s.lastIndexOf('/'), s.lastIndexOf(".class"));
        Class AppletClass = ucl.loadClass(classname, true);
        Applet apl = (Applet) AppletClass.newInstance();
        JFrame f = new JFrame();
        f.setSize(200, 200);
        f.add("Center", apl);
        apl.init();
        apl.start();
        f.setVisible(true);
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:com.pervasive07.MsgReader.java

public static void main(String[] args) throws Exception {
    String source = null;/* ww w . j a  v  a  2  s. co m*/
    Vector v = new Vector();
    if (args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-comm")) {
                source = args[++i];
            } else {
                String className = args[i];
                try {
                    Class c = Class.forName(className);
                    Object packet = c.newInstance();
                    Message msg = (Message) packet;
                    if (msg.amType() < 0) {
                        System.err.println(className + " does not have an AM type - ignored");
                    } else {
                        v.addElement(msg);
                    }
                } catch (Exception e) {
                    System.err.println(e);
                }
            }
        }
    } else if (args.length != 0) {
        usage();
        System.exit(1);
    }

    MsgReader mr = new MsgReader(source);
    Enumeration msgs = v.elements();
    while (msgs.hasMoreElements()) {
        Message m = (Message) msgs.nextElement();
        mr.addMsgType(m);
    }
    mr.start();
}

From source file:MinAppletviewer.java

public static void main(String args[]) throws Exception {
    AppSupport theAppSupport = new AppSupport();
    JFrame f = new JFrame();
    URL toload = new URL(args[0]);
    String host = toload.getHost();
    int port = toload.getPort();
    String protocol = toload.getProtocol();
    String path = toload.getFile();
    int join = path.lastIndexOf('/');
    String file = path.substring(join + 1);
    path = path.substring(0, join + 1);//from  w ww  .java2s.c  om

    theAppSupport.setCodeBase(new URL(protocol, host, port, path));
    theAppSupport.setDocumentBase(theAppSupport.getCodeBase());

    URL[] bases = { theAppSupport.getCodeBase() };
    URLClassLoader loader = new URLClassLoader(bases);
    Class theAppletClass = loader.loadClass(file);
    Applet theApplet = (Applet) (theAppletClass.newInstance());

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    f.add(theApplet, BorderLayout.CENTER);

    theApplet.setStub(theAppSupport);

    f.setSize(200, 200);
    f.setVisible(true);
    theApplet.init();
    theApplet.start();
}

From source file:com.spotify.cassandra.opstools.CountTombstones.java

/**
 * Counts the number of tombstones, per row, in a given SSTable
 *
 * Assumes RandomPartitioner, standard columns and UTF8 encoded row keys
 *
 * Does not require a cassandra.yaml file or system tables.
 *
 * @param args command lines arguments//ww  w .j av a2 s.c om
 *
 * @throws java.io.IOException on failure to open/read/write files or output streams
 */
public static void main(String[] args) throws IOException, ParseException {
    String usage = String.format("Usage: %s [-l] <sstable> [<sstable> ...]%n", CountTombstones.class.getName());

    final Options options = new Options();
    options.addOption("l", "legend", false, "Include column name explanation");
    options.addOption("p", "partitioner", true, "The partitioner used by database");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.getArgs().length < 1) {
        System.err.println("You must supply at least one sstable");
        System.err.println(usage);
        System.exit(1);
    }

    // Fake DatabaseDescriptor settings so we don't have to load cassandra.yaml etc
    Config.setClientMode(true);
    String partitionerName = String.format("org.apache.cassandra.dht.%s",
            options.hasOption("p") ? options.getOption("p") : "RandomPartitioner");
    try {
        Class<?> clazz = Class.forName(partitionerName);
        IPartitioner partitioner = (IPartitioner) clazz.newInstance();
        DatabaseDescriptor.setPartitioner(partitioner);
    } catch (Exception e) {
        throw new RuntimeException("Can't instantiate partitioner " + partitionerName);
    }

    PrintStream out = System.out;

    for (String arg : cmd.getArgs()) {
        String ssTableFileName = new File(arg).getAbsolutePath();

        Descriptor descriptor = Descriptor.fromFilename(ssTableFileName);

        run(descriptor, cmd, out);
    }

    System.exit(0);
}

From source file:gis.proj.drivers.SnyderTest.java

public static void main(String... args) {
    SnyderTest sfTest = new SnyderTest();
    JCommander jc = new JCommander(sfTest);

    try {/*  w  ww.  ja  v  a2s. c  om*/
        jc.parse(args);
    } catch (Exception e) {
        jc.usage();
        System.exit(-10);
    }

    Snyder.printLicenseInformation("SnyderTest");

    double[][] fVal = null; // forward values
    double[][] iVal = null; // inverse values

    Ellipsoid ellip;
    Datum datum;
    Projection proj;

    ArrayList<Fiducial> testData = null;

    try {
        testData = Snyder.fromJSON(new TypeReference<ArrayList<Fiducial>>() {
        }, sfTest.ifName);
    } catch (Exception e) {
    }

    if (testData != null) {
        for (Fiducial sf : testData) {
            ellip = null;
            datum = null;
            proj = null;

            ellip = EllipsoidFactory.getInstance().getEllipsoid(sf.getEllipsoid());

            datum = new Datum();

            for (Entry<String, String> entry : sf.getDatum().entrySet()) {
                datum.setUserOverrideProperty(entry.getKey(),
                        Snyder.parseDatumVal(entry.getValue().toLowerCase()));
            }

            try {
                Class<?> cls = Class.forName(sf.getProjection());
                proj = (Projection) cls.newInstance();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            fVal = proj.forward(new double[] { sf.getLon() * SnyderMath.DEG_TO_RAD },
                    new double[] { sf.getLat() * SnyderMath.DEG_TO_RAD }, ellip, datum);

            iVal = proj.inverse(new double[] { fVal[0][0] }, new double[] { fVal[1][0] }, ellip, datum);

            iVal[0][0] *= SnyderMath.RAD_TO_DEG;
            iVal[1][0] *= SnyderMath.RAD_TO_DEG;

            sf.setPassed(fVal[0][0], fVal[1][0], iVal[0][0], iVal[1][0]);
        }

        try {

            if (sfTest.ofName != null)
                sfTest.om.writeValue(new File(sfTest.ofName), testData);

        } catch (Exception e) {
            System.out.println("Couldn't write the fiducial data results, of=" + sfTest.ofName);
            System.exit(-1);
        }

        System.out.print("\n**********************************************************************\n");
        System.out.print("SNYDER TEST SUMMARY");
        System.out.print("\n**********************************************************************\n");
        System.out.println("\n\t  Total test cases : " + testData.size());
    } else {
        System.out.println("Couldn't load the fiducial data, if=" + sfTest.ifName);
        System.exit(-1);
    }
}

From source file:ClassForName.java

public static void main(String[] av) {
    Class c = null;
    Object o = null;/*w w w.j  a  va  2 s.co  m*/
    try {
        // Load the class, return a Class for it
        c = Class.forName("java.awt.Frame");
        // Construct an object, as if new Type()
        o = c.newInstance();
    } catch (Exception e) {
        System.err.println("That didn't work. " + " Try something else" + e);
    }
    if (o != null && o instanceof Frame) {
        Frame f = (Frame) o;
        f.setTitle("Testing");
        f.setVisible(true);
    } else
        throw new IllegalArgumentException("Huh? What gives?");
}

From source file:Main.java

static public void main(String args[]) throws Exception {
    URL myurl[] = { new URL("file:///C:/CH3/ClassLoader/web/"), new URL("http://www.java2s.edu/~xyx/test/") };
    URLClassLoader x = new URLClassLoader(myurl);
    Class c = x.loadClass("TestURL");

    Class getArg1[] = { (new String[1]).getClass() };
    Method m = c.getMethod("main", getArg1);
    String[] my1 = { "arg1 passed", "arg2 passed" };
    Object myarg1[] = { my1 };/*from w ww. j  av a  2s.  c o  m*/
    m.invoke(null, myarg1);

    Object ob = c.newInstance();
    Class arg2[] = {};
    Method m2 = c.getMethod("tt", arg2);
    m2.invoke(ob, null);

    Class arg3[] = { (new String()).getClass(), int.class };
    Method m3 = c.getMethod("tt", arg3);
    Object myarg2[] = { "Arg1", new Integer(100) };
    m3.invoke(ob, myarg2);
}