Java Java String Format toJavaTypeIdentifier(String string)

Here you can find the source of toJavaTypeIdentifier(String string)

Description

Fashion a type identifier from the given string.

License

LGPL

Parameter

Parameter Description
string a parameter

Return

A valid java type identifier. Title case.

Declaration

public static String toJavaTypeIdentifier(String string) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    /**//from   w  w w  . j  av a 2s  . c o  m
     * Fashion a type identifier from the given string.
     * @param string
     * @return   A valid java type identifier.  Title case.
     */
    public static String toJavaTypeIdentifier(String string) {
        StringBuilder sb = new StringBuilder(toJavaInstanceIdentifier(string));
        sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
        return sb.toString();
    }

    /**
     * Fashion an instance identifier from the given string.
     * @param string
     * @return   A valid java instance identifier.  Camel case.
     */
    public static String toJavaInstanceIdentifier(String string) {
        StringBuilder sb = new StringBuilder(string);
        removeInvalidCharacters(sb);
        sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
        return sb.toString();
    }

    private static void removeInvalidCharacters(StringBuilder sb) {
        int i = 0;
        boolean whiteSpaceOrUnderscore = false;
        while (i < sb.length()) {
            if (i == 0) {
                if (Character.isJavaIdentifierStart(sb.charAt(0)) && (sb.charAt(0) != '_')) {
                    i++;
                } else {
                    sb.deleteCharAt(0);
                }
            } else {
                if (Character.isJavaIdentifierPart(sb.charAt(i)) && (sb.charAt(i) != '_')) {
                    if (whiteSpaceOrUnderscore) {
                        sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
                    }
                    whiteSpaceOrUnderscore = false;
                    i++;
                } else {
                    if (Character.isWhitespace(sb.charAt(i)) || (sb.charAt(i) == '_')) {
                        whiteSpaceOrUnderscore = true;
                    }
                    sb.deleteCharAt(i);
                }
            }
        }
    }
}

Related

  1. toJavaStaticIdentifier(String string)
  2. toJavaString(final String s)
  3. toJavaString(String buf)
  4. toJavaString(String text)
  5. toJavaTime(double time)
  6. toJavaTypeName(String edmTypeName)
  7. toJavaTypes(Class clazz, String value)
  8. toJavaVariable(Class compClass, String name)