Here you can find the source of getSetterMethodFromGetter(final Method getter)
Parameter | Description |
---|---|
getter | The getter Method |
Parameter | Description |
---|---|
NoSuchMethodException | If the setter method does not exist |
SecurityException | If the setter method is not accessible |
public static Method getSetterMethodFromGetter(final Method getter) throws SecurityException, NoSuchMethodException
//package com.java2s; /*//from w ww .ja v a 2 s.c o m * Copyright 2008 Werner Guttmann, Peter Schmidt * * 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. */ import java.lang.reflect.Method; public class Main { /** * Return a setter {@link Method} for a given getter {@link Method}. * * @param getter * The getter {@link Method} * @return The setter Method for the given getter Method. * @throws NoSuchMethodException * If the setter method does not exist * @throws SecurityException * If the setter method is not accessible */ public static Method getSetterMethodFromGetter(final Method getter) throws SecurityException, NoSuchMethodException { if (!isGetter(getter)) { throw new IllegalArgumentException("Method is not a getter method!"); } String[] prefixes = { "get", "is" }; String setterName; for (String prefix : prefixes) { if (getter.getName().startsWith(prefix)) { String name = getter.getName().substring(prefix.length()); setterName = "set" + name; return getter.getDeclaringClass().getDeclaredMethod(setterName, getter.getReturnType()); } } throw new IllegalArgumentException("Method name does not start with 'get' or 'is'!"); } /** * Convenience method to check whether a {@link Method} is a getter method, * i.e. starts with "get" or "is". * * @param method * the {@link Method} to check. * @return true if the methods name starts with "get" or "is" (Java Beans * convention). */ public static boolean isGetter(final Method method) { if (method.getName().startsWith("get") || method.getName().startsWith("is")) { return true; } return false; } }