Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern METHOD_NAME_TO_ATTR_NAME_PATTERN = Pattern.compile("[A-Z]+");

    /**
     * Converts a method name to an attribute name, e.g. getFooBar() --> foo_bar, isFlag --> flag.
     * @param methodName
     * @return
     */
    public static String methodNameToAttributeName(final String methodName) {
        String name = methodName;
        if ((methodName.startsWith("get") || methodName.startsWith("set")) && methodName.length() > 3)
            name = methodName.substring(3);
        else if (methodName.startsWith("is") && methodName.length() > 2)
            name = methodName.substring(2);

        // Pattern p=Pattern.compile("[A-Z]+");
        Matcher m = METHOD_NAME_TO_ATTR_NAME_PATTERN.matcher(name);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            int start = m.start(), end = m.end();
            String str = name.substring(start, end).toLowerCase();
            if (str.length() > 1) {
                String tmp1 = str.substring(0, str.length() - 1);
                String tmp2 = str.substring(str.length() - 1);
                str = tmp1 + "_" + tmp2;
            }
            if (start == 0) {
                m.appendReplacement(sb, str);
            } else
                m.appendReplacement(sb, "_" + str);
        }
        m.appendTail(sb);
        return sb.length() > 0 ? sb.toString() : methodName;
    }
}