Java examples for Reflection:Method Name
Returns the property name for a method.
/*/*from ww w. ja va 2 s . c o m*/ * Copyright 2002-2006,2009 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.java2s; import java.lang.reflect.Method; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static final Pattern SETTER_PATTERN = Pattern .compile("set([A-Z][A-Za-z0-9]*)$"); private static final Pattern GETTER_PATTERN = Pattern .compile("(get|is|has)([A-Z][A-Za-z0-9]*)$"); /** * Returns the property name for a method. * This method is independant from property fields. * * @param method The method to get the property name for. * @return the property name for given method; null if non could be resolved. */ public static String resolvePropertyName(Method method) { Matcher matcher = SETTER_PATTERN.matcher(method.getName()); if (matcher.matches() && method.getParameterTypes().length == 1) { String raw = matcher.group(1); return raw.substring(0, 1).toLowerCase() + raw.substring(1); } matcher = GETTER_PATTERN.matcher(method.getName()); if (matcher.matches() && method.getParameterTypes().length == 0) { String raw = matcher.group(2); return raw.substring(0, 1).toLowerCase() + raw.substring(1); } return null; } }