Example usage for java.lang Class getName

List of usage examples for java.lang Class getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String .

Usage

From source file:org.syncope.hibernate.HibernateEnhancer.java

public static void main(final String[] args) throws Exception {

    if (args.length != 1) {
        throw new IllegalArgumentException("Expecting classpath as single argument");
    }//w  w w.  j a va  2 s  .c o  m

    ClassPool classPool = ClassPool.getDefault();
    classPool.appendClassPath(args[0]);

    PathMatchingResourcePatternResolver resResolver = new PathMatchingResourcePatternResolver(
            classPool.getClassLoader());
    CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();

    for (Resource resource : resResolver.getResources("classpath*:org/syncope/core/**/*.class")) {

        MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
        if (metadataReader.getAnnotationMetadata().isAnnotated(Entity.class.getName())) {

            Class entity = Class.forName(metadataReader.getClassMetadata().getClassName());
            classPool.appendClassPath(new ClassClassPath(entity));
            CtClass ctClass = ClassPool.getDefault().get(entity.getName());
            if (ctClass.isFrozen()) {
                ctClass.defrost();
            }
            ClassFile classFile = ctClass.getClassFile();
            ConstPool constPool = classFile.getConstPool();

            for (Field field : entity.getDeclaredFields()) {
                if (field.isAnnotationPresent(Lob.class)) {
                    AnnotationsAttribute typeAttr = new AnnotationsAttribute(constPool,
                            AnnotationsAttribute.visibleTag);
                    Annotation typeAnnot = new Annotation("org.hibernate.annotations.Type", constPool);
                    typeAnnot.addMemberValue("type",
                            new StringMemberValue("org.hibernate.type.StringClobType", constPool));
                    typeAttr.addAnnotation(typeAnnot);

                    CtField lobField = ctClass.getDeclaredField(field.getName());
                    lobField.getFieldInfo().addAttribute(typeAttr);
                }
            }

            ctClass.writeFile(args[0]);
        }
    }
}

From source file:MethodCountingHandler.java

/** 
 * Run the demonstration./*from w w w .  java 2 s.  com*/
 *
 * @param args Command line arguments (ignored).
 */
public static final void main(final String[] args) {
    SomeClass proxy = SomeClassFactory.getDynamicSomeClassProxy();
    System.out.println(proxy.getClass().getName());
    try {
        Class cl = Class.forName("$Proxy0"); // <== Dangerous!
        System.out.println(cl.getName());
    } catch (final ClassNotFoundException ex) {
        ex.printStackTrace();
    }
}

From source file:Spy.java

public static void main(String... args) {
    try {/*from www  .ja v  a  2 s  . c  o m*/
        Class<?> c = Class.forName(args[0]);
        int searchMods = 0x0;
        for (int i = 1; i < args.length; i++) {
            searchMods |= modifierFromString(args[i]);
        }

        Field[] flds = c.getDeclaredFields();
        out.format("Fields in Class '%s' containing modifiers:  %s%n", c.getName(),
                Modifier.toString(searchMods));
        boolean found = false;
        for (Field f : flds) {
            int foundMods = f.getModifiers();
            // Require all of the requested modifiers to be present
            if ((foundMods & searchMods) == searchMods) {
                out.format("%-8s [ synthetic=%-5b enum_constant=%-5b ]%n", f.getName(), f.isSynthetic(),
                        f.isEnumConstant());
                found = true;
            }
        }

        if (!found) {
            out.format("No matching fields%n");
        }

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

From source file:org.eclipse.swt.snippets.SnippetLauncher.java

public static void main(String[] args) {
    File sourceDir = SnippetsConfig.SNIPPETS_SOURCE_DIR;
    boolean hasSource = sourceDir.exists();
    int count = 500;
    if (hasSource) {
        File[] files = sourceDir.listFiles();
        if (files.length > 0)
            count = files.length;//from  w w w  .  jav a2s.c o  m
    }
    for (int i = 1; i < count; i++) {
        if (SnippetsConfig.isPrintingSnippet(i))
            continue; // avoid printing to printer
        String className = "Snippet" + i;
        Class<?> clazz = null;
        try {
            clazz = Class.forName(SnippetsConfig.SNIPPETS_PACKAGE + "." + className);
        } catch (ClassNotFoundException e) {
        }
        if (clazz != null) {
            System.out.println("\n" + clazz.getName());
            if (hasSource) {
                File sourceFile = new File(sourceDir, className + ".java");
                try (FileReader reader = new FileReader(sourceFile);) {
                    char[] buffer = new char[(int) sourceFile.length()];
                    reader.read(buffer);
                    String source = String.valueOf(buffer);
                    int start = source.indexOf("package");
                    start = source.indexOf("/*", start);
                    int end = source.indexOf("* For a list of all");
                    System.out.println(source.substring(start, end - 3));
                    boolean skip = false;
                    String platform = SWT.getPlatform();
                    if (source.contains("PocketPC")) {
                        platform = "PocketPC";
                        skip = true;
                    } else if (source.contains("OpenGL")) {
                        platform = "OpenGL";
                        skip = true;
                    } else if (source.contains("JavaXPCOM")) {
                        platform = "JavaXPCOM";
                        skip = true;
                    } else {
                        String[] platforms = { "win32", "gtk" };
                        for (int p = 0; p < platforms.length; p++) {
                            if (!platforms[p].equals(platform) && source.contains("." + platforms[p])) {
                                platform = platforms[p];
                                skip = true;
                                break;
                            }
                        }
                    }
                    if (skip) {
                        System.out.println("...skipping " + platform + " example...");
                        continue;
                    }
                } catch (Exception e) {
                }
            }
            Method method = null;
            String[] param = SnippetsConfig.getSnippetArguments(i);
            try {
                method = clazz.getMethod("main", param.getClass());
            } catch (NoSuchMethodException e) {
                System.out.println("   Did not find main(String [])");
            }
            if (method != null) {
                try {
                    method.invoke(clazz, new Object[] { param });
                } catch (IllegalAccessException e) {
                    System.out.println("   Failed to launch (illegal access)");
                } catch (IllegalArgumentException e) {
                    System.out.println("   Failed to launch (illegal argument to main)");
                } catch (InvocationTargetException e) {
                    System.out.println("   Exception in Snippet: " + e.getTargetException());
                }
            }
        }
    }
}

From source file:ReflectionTest.java

public static void main(String[] args) {
    // read class name from command line args or user input
    String name;/*from   www . jav a2  s  . co m*/
    if (args.length > 0)
        name = args[0];
    else {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter class name (e.g. java.util.Date): ");
        name = in.next();
    }

    try {
        // print class name and superclass name (if != Object)
        Class cl = Class.forName(name);
        Class supercl = cl.getSuperclass();
        String modifiers = Modifier.toString(cl.getModifiers());
        if (modifiers.length() > 0)
            System.out.print(modifiers + " ");
        System.out.print("class " + name);
        if (supercl != null && supercl != Object.class)
            System.out.print(" extends " + supercl.getName());

        System.out.print("\n{\n");
        printConstructors(cl);
        System.out.println();
        printMethods(cl);
        System.out.println();
        printFields(cl);
        System.out.println("}");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.exit(0);
}

From source file:MethodInspector.java

public static void main(String[] arguments) {
    Class inspect;//from  w  w  w. ja  va 2  s . c  o m
    try {
        if (arguments.length > 0)
            inspect = Class.forName(arguments[0]);
        else
            inspect = Class.forName("MethodInspector");
        Method[] methods = inspect.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            Method methVal = methods[i];
            Class returnVal = methVal.getReturnType();
            int mods = methVal.getModifiers();
            String modVal = Modifier.toString(mods);
            Class[] paramVal = methVal.getParameterTypes();
            StringBuffer params = new StringBuffer();
            for (int j = 0; j < paramVal.length; j++) {
                if (j > 0)
                    params.append(", ");
                params.append(paramVal[j].getName());
            }
            System.out.println("Method: " + methVal.getName() + "()");
            System.out.println("Modifiers: " + modVal);
            System.out.println("Return Type: " + returnVal.getName());
            System.out.println("Parameters: " + params + "\n");
        }
    } catch (ClassNotFoundException c) {
        System.out.println(c.toString());
    }
}

From source file:net.dontdrinkandroot.lastfm.api.CheckImplementationStatus.java

public static void main(final String[] args) throws DocumentException, IOException {

    CheckImplementationStatus.xmlReader = new Parser();
    CheckImplementationStatus.saxReader = new SAXReader(CheckImplementationStatus.xmlReader);

    final String packagePrefix = "net.dontdrinkandroot.lastfm.api.model.";

    final Map<String, Map<String, URL>> packages = CheckImplementationStatus.parseOverview();

    final StringBuffer html = new StringBuffer();
    html.append("<html>\n");
    html.append("<head>\n");
    html.append("<title>Implementation Status</title>\n");
    html.append("</head>\n");
    html.append("<body>\n");
    html.append("<h1>Implementation Status</h1>\n");

    final StringBuffer wiki = new StringBuffer();

    int numImplemented = 0;
    int numTested = 0;
    int numMethods = 0;

    final List<String> packageList = new ArrayList<String>(packages.keySet());
    Collections.sort(packageList);

    for (final String pkg : packageList) {

        System.out.println("Parsing " + pkg);
        html.append("<h2>" + pkg + "</h2>\n");
        wiki.append("\n===== " + pkg + " =====\n\n");

        Class<?> modelClass = null;
        final String className = packagePrefix + pkg;
        try {//from  www. java 2  s  .c  o  m
            modelClass = Class.forName(className);
            System.out.println("\tClass " + modelClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + className + ": DOES NOT exist");
        }

        Class<?> testClass = null;
        final String testClassName = packagePrefix + pkg + "Test";
        try {
            testClass = Class.forName(testClassName);
            System.out.println("\tTestClass " + testClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + testClassName + ": TestClass for DOES NOT exist");
        }

        final List<String> methods = new ArrayList<String>(packages.get(pkg).keySet());
        Collections.sort(methods);

        final Method[] classMethods = modelClass.getMethods();
        final Method[] testMethods = testClass.getMethods();

        html.append("<table>\n");
        html.append("<tr><th>Method</th><th>Implemented</th><th>Tested</th></tr>\n");
        wiki.append("^ Method  ^ Implemented  ^ Tested  ^\n");

        numMethods += methods.size();

        for (final String method : methods) {

            System.out.println("\t\t parsing " + method);

            html.append("<tr>\n");
            html.append("<td>" + method + "</td>\n");
            wiki.append("| " + method + "  ");

            boolean classMethodFound = false;
            for (final Method classMethod : classMethods) {
                if (classMethod.getName().equals(method)) {
                    classMethodFound = true;
                    break;
                }
            }

            if (classMethodFound) {
                System.out.println("\t\t\tMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  ");
                numImplemented++;
            } else {
                System.out.println("\t\t\t" + method + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  ");
            }

            boolean testMethodFound = false;
            final String testMethodName = "test" + StringUtils.capitalize(method);
            for (final Method testMethod : testMethods) {
                if (testMethod.getName().equals(testMethodName)) {
                    testMethodFound = true;
                    break;
                }
            }

            if (testMethodFound) {
                System.out.println("\t\t\tTestMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  |\n");
                numTested++;
            } else {
                System.out.println("\t\t\t" + testMethodName + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  |\n");
            }

            html.append("</tr>\n");

        }

        html.append("</table>\n");

        // for (String methodName : methods) {
        // URL url = pkg.getValue().get(methodName);
        // System.out.println("PARSING: " + pkg.getKey() + "." + methodName + ": " + url);
        // String html = loadIntoString(url);
        // String description = null;
        // Matcher descMatcher = descriptionPattern.matcher(html);
        // if (descMatcher.find()) {
        // description = descMatcher.group(1).trim();
        // }
        // boolean post = false;
        // Matcher postMatcher = postPattern.matcher(html);
        // if (postMatcher.find()) {
        // post = true;
        // }
        // Matcher paramsMatcher = paramsPattern.matcher(html);
        // List<String[]> params = new ArrayList<String[]>();
        // boolean authenticated = false;
        // if (paramsMatcher.find()) {
        // String paramsString = paramsMatcher.group(1);
        // Matcher paramMatcher = paramPattern.matcher(paramsString);
        // while (paramMatcher.find()) {
        // String[] param = new String[3];
        // param[0] = paramMatcher.group(1);
        // param[1] = paramMatcher.group(3);
        // param[2] = paramMatcher.group(5);
        // // System.out.println(paramMatcher.group(1) + "|" + paramMatcher.group(3) + "|" +
        // paramMatcher.group(5));
        // if (param[0].equals("")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_key")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_sig")) {
        // authenticated = true;
        // } else {
        // params.add(param);
        // }
        // }
        // }
        // }
        // count++;
        //
    }

    html.append("<hr />");
    html.append("<p>" + numImplemented + "/" + numMethods + " implemented (" + numImplemented * 100 / numMethods
            + "%)</p>");
    html.append("<p>" + numTested + "/" + numMethods + " tested (" + numTested * 100 / numMethods + "%)</p>");

    html.append("</body>\n");
    html.append("</html>\n");

    FileOutputStream out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.html"));
    IOUtils.write(html, out);
    IOUtils.closeQuietly(out);

    out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.wiki.txt"));
    IOUtils.write(wiki, out);
    IOUtils.closeQuietly(out);
}

From source file:ReflectClass.java

public static void main(String args[]) {
    Constructor cn[];/*from  w  w w .j  av  a  2s .  co  m*/
    Class cc[];
    Method mm[];
    Field ff[];
    Class c = null;
    Class supClass;
    String x, y, s1, s2, s3;
    Hashtable classRef = new Hashtable();

    if (args.length == 0) {
        System.out.println("Please specify a class name on the command line.");
        System.exit(1);
    }

    try {
        c = Class.forName(args[0]);
    } catch (ClassNotFoundException ee) {
        System.out.println("Couldn't find class '" + args[0] + "'");
        System.exit(1);
    }

    /*
     * Step 0: If our name contains dots we're in a package so put
     * that out first.
     */
    x = c.getName();
    if (x.lastIndexOf(".") != -1) {
        y = x.substring(0, x.lastIndexOf("."));
        System.out.println("package " + y + ";\n\r");
    }

    /*
     * Let's use the Reflection API to sift through what is
     * inside this class.
     *
     * Step 1: Collect referenced classes
     * This step is used so that I can regenerate the import statements.
     * It isn't strictly required of course, Java works just fine with
     * fully qualified object class names, but it looks better when you
     * use 'String' rather than 'java.lang.String' as the return type.
     */

    ff = c.getDeclaredFields();
    for (int i = 0; i < ff.length; i++) {
        x = tName(ff[i].getType().getName(), classRef);
    }

    cn = c.getDeclaredConstructors();
    for (int i = 0; i < cn.length; i++) {
        Class cx[] = cn[i].getParameterTypes();
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                x = tName(cx[j].getName(), classRef);
            }
        }
    }

    mm = c.getDeclaredMethods();
    for (int i = 0; i < mm.length; i++) {
        x = tName(mm[i].getReturnType().getName(), classRef);
        Class cx[] = mm[i].getParameterTypes();
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                x = tName(cx[j].getName(), classRef);
            }
        }
    }

    // Don't import ourselves ...
    classRef.remove(c.getName());

    /*
     * Step 2: Start class description generation, start by printing
     *  out the import statements.
     *
     * This is the line that goes 'public SomeClass extends Foo {'
     */
    for (Enumeration e = classRef.keys(); e.hasMoreElements();) {
        System.out.println("import " + e.nextElement() + ";");
    }
    System.out.println();

    /*
     * Step 3: Print the class or interface introducer. We use
     * a convienience method in Modifer to print the whole string.
     */
    int mod = c.getModifiers();
    System.out.print(Modifier.toString(mod));

    if (Modifier.isInterface(mod)) {
        System.out.print(" interface ");
    } else {
        System.out.print(" class ");
    }
    System.out.print(tName(c.getName(), null));

    supClass = c.getSuperclass();
    if (supClass != null) {
        System.out.print(" extends " + tName(supClass.getName(), classRef));
    }
    System.out.println(" {");

    /*
     * Step 4: Print out the fields (internal class members) that are declared
     * by this class.
     *
     * Fields are of the form [Modifiers] [Type] [Name] ;
     */

    System.out.println("\n\r/*\n\r * Field Definitions.\r\n */");
    for (int i = 0; i < ff.length; i++) {
        Class ctmp = ff[i].getType();
        int md = ff[i].getModifiers();

        System.out.println("    " + Modifier.toString(md) + " " + tName(ff[i].getType().getName(), null) + " "
                + ff[i].getName() + ";");
    }

    /*
     * Step 5: Print out the constructor declarations.
     *
     * We note the name of the class which is the 'name' for all
     * constructors. Also there is no type, so the definition is
     * simplye [Modifiers] ClassName ( [ Parameters ] ) { }
     *
     */
    System.out.println("\n\r/*\n\r * Declared Constructors. \n\r */");
    x = tName(c.getName(), null);
    for (int i = 0; i < cn.length; i++) {
        int md = cn[i].getModifiers();
        System.out.print("    " + Modifier.toString(md) + " " + x);

        Class cx[] = cn[i].getParameterTypes();
        System.out.print("( ");
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                System.out.print(tName(cx[j].getName(), null));
                if (j < (cx.length - 1))
                    System.out.print(", ");
            }
        }
        System.out.print(") ");
        System.out.println("{ ... }");
    }

    /*
     * Step 6: Print out the method declarations.
     *
     * Now methods have a name, a return type, and an optional
     * set of parameters so they are :
     *  [modifiers] [type] [name] ( [optional parameters] ) { }
     */
    System.out.println("\n\r/*\n\r * Declared Methods.\n\r */");
    for (int i = 0; i < mm.length; i++) {
        int md = mm[i].getModifiers();
        System.out.print("    " + Modifier.toString(md) + " " + tName(mm[i].getReturnType().getName(), null)
                + " " + mm[i].getName());

        Class cx[] = mm[i].getParameterTypes();
        System.out.print("( ");
        if (cx.length > 0) {
            for (int j = 0; j < cx.length; j++) {
                System.out.print(tName(cx[j].getName(), classRef));
                if (j < (cx.length - 1))
                    System.out.print(", ");
            }
        }
        System.out.print(") ");
        System.out.println("{ ... }");
    }

    /*
     * Step 7: Print out the closing brace and we're done!
     */
    System.out.println("}");
}

From source file:SIFT_Volume_Stitching.java

public static void main(String[] args) {
    // set the plugins.dir property to make the plugin appear in the Plugins menu
    Class<?> clazz = SIFT_Volume_Stitching.class;
    String url = clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class").toString();
    String pluginsDir = url.substring("file:".length(),
            url.length() - clazz.getName().length() - ".class".length());
    System.setProperty("plugins.dir", pluginsDir);

    // start ImageJ
    new ImageJ();

    // open the Clown sample
    ImagePlus image1 = IJ.openImage("https://www.creatis.insa-lyon.fr/~frindel/BackStack115.tif");
    ImagePlus image2 = IJ.openImage("https://www.creatis.insa-lyon.fr/~frindel/FrontStack.tif");
    image1.show();/*from   w  ww.j a va 2s.com*/
    image2.show();

    // run the plugin
    IJ.runPlugIn(clazz.getName(), "");
}

From source file:at.tuwien.ifs.somtoolbox.doc.RunnablesReferenceCreator.java

public static void main(String[] args) {
    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);//from ww  w. j  a  v  a  2s.  co m
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    StringBuilder sbIndex = new StringBuilder(runnables.size() * 50);
    StringBuilder sbDetails = new StringBuilder(runnables.size() * 200);

    sbIndex.append("\n<table border=\"0\">\n");

    Type lastType = null;

    for (Class<? extends SOMToolboxApp> c : runnables) {
        try {
            // Ignore abstract classes and interfaces
            if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
                continue;
            }

            Type type = Type.getType(c);
            if (type != lastType) {
                sbIndex.append("  <tr> <td colspan=\"2\"> <h5> " + type + " Applications </h5> </td> </tr>\n");
                sbDetails.append("<h2> " + type + " Applications </h2>\n");
                lastType = type;
            }
            String descr = "N/A";
            try {
                descr = (String) c.getDeclaredField("DESCRIPTION").get(null);
            } catch (Exception e) {
            }
            String longDescr = "descr";
            try {
                longDescr = (String) c.getDeclaredField("LONG_DESCRIPTION").get(null);
            } catch (Exception e) {
            }

            sbIndex.append("  <tr>\n");
            sbIndex.append("    <td> <a href=\"#").append(c.getSimpleName()).append("\">")
                    .append(c.getSimpleName()).append("</a> </td>\n");
            sbIndex.append("    <td> ").append(descr).append(" </td>\n");
            sbIndex.append("  </tr>\n");

            sbDetails.append("<h3 id=\"").append(c.getSimpleName()).append("\">").append(c.getSimpleName())
                    .append("</h3>\n");
            sbDetails.append("<p>").append(longDescr).append("</p>\n");

            try {
                Parameter[] options = (Parameter[]) c.getField("OPTIONS").get(null);
                JSAP jsap = AbstractOptionFactory.registerOptions(options);
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(os);
                AbstractOptionFactory.printHelp(jsap, c.getName(), ps);
                sbDetails.append("<pre>").append(StringEscapeUtils.escapeHtml(os.toString())).append("</pre>");
            } catch (Exception e1) { // we didn't find the options => let the class be invoked ...
            }

        } catch (SecurityException e) {
            // Should not happen - no Security
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    sbIndex.append("</table>\n\n");
    System.out.println(sbIndex);
    System.out.println(sbDetails);
}