get Java Bean Property Name from Method name - Java Reflection

Java examples for Reflection:Java Bean

Description

get Java Bean Property Name from Method name

Demo Code

/**//from w  w w .  j  ava  2s  . co  m
 * JLibs: Common Utilities for Java
 * Copyright (C) 2009  Santhosh Kumar T <santhosh.tekuri@gmail.com>
 *
 * 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.
 */
//package com.java2s;

import java.util.Locale;

public class Main {
    public static void main(String[] argv) throws Exception {
        String methodName = "java2s.com";
        System.out.println(getPropertyName(methodName));
    }

    /** prefix used by non-boolean getter methods */
    public static final String GET = "get";
    /** prefix used by boolean getter methods */
    public static final String IS = "is";
    /** prefix used by setter methods */
    public static final String SET = "set";

    @SuppressWarnings({ "ConstantConditions" })
    public static String getPropertyName(String methodName) {
        String suffix;
        if (methodName.startsWith(GET) || methodName.startsWith(SET))
            suffix = methodName.substring(3);
        else if (methodName.startsWith(IS))
            suffix = methodName.substring(2);
        else
            throw new IllegalArgumentException("invalid method name: "
                    + methodName);

        switch (suffix.length()) {
        case 0:
            throw new IllegalArgumentException("invalid method name: "
                    + methodName);
        case 1:
            return suffix.toLowerCase(Locale.ENGLISH);
        default:
            char char0 = suffix.charAt(0);
            boolean upper0 = Character.isUpperCase(char0);
            char char1 = suffix.charAt(1);
            boolean upper1 = Character.isUpperCase(char1);
            if (upper0 && upper1) // getXCordinate() ==> XCoordinate
                return suffix;
            if (upper0 && !upper1) // getXcoordinate() ==> xcoordinate
                return Character.toLowerCase(char0) + suffix.substring(1);
            if (!upper0 && upper1) // getxCoordinate() ==> xCoordinate
                return suffix;
            throw new IllegalArgumentException("invalid method name: "
                    + methodName);
        }
    }
}

Related Tutorials