Java Java String Format toJavaVariable(Class compClass, String name)

Here you can find the source of toJavaVariable(Class compClass, String name)

Description

Converts the given variable name to a valid Java variable.

License

Open Source License

Declaration

public static String toJavaVariable(Class compClass, String name) 

Method Source Code

//package com.java2s;
/*//www.jav  a 2 s  .c  o m
 * Copyright (C) 2005 Jeff Tassin
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

public class Main {
    /**
     * Converts the given variable name to a valid Java variable. If any symbols
     * are found that are invalid symbols, they are removed.
     */
    public static String toJavaVariable(Class compClass, String name) {
        if (name != null)
            name = name.trim();

        if (name == null || name.length() == 0) {
            name = trimPackage(compClass);
            name = name.toLowerCase();
        }

        StringBuffer sbuff = new StringBuffer();
        for (int index = 0; index < name.length(); index++) {
            char c = name.charAt(index);
            if (index == 0 && !Character.isJavaIdentifierStart(c)) {
                c = '_';
            } else if (!Character.isJavaIdentifierPart(c)) {
                c = '_';
            }
            sbuff.append(c);
        }
        return sbuff.toString();
    }

    public static String trimPackage(Class c) {
        if (c == null)
            return "";
        String cname = c.getName();
        int pos = cname.lastIndexOf('.');
        if (pos >= 0)
            cname = cname.substring(pos + 1, cname.length());
        return cname;
    }
}

Related

  1. toJavaString(String text)
  2. toJavaTime(double time)
  3. toJavaTypeIdentifier(String string)
  4. toJavaTypeName(String edmTypeName)
  5. toJavaTypes(Class clazz, String value)