Java tutorial
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.angstoverseer.util; import com.angstoverseer.service.command.router.CommandRouterImpl; import org.apache.commons.lang.StringUtils; import org.apache.tapestry5.func.F; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; public final class ReflectionUtil { private ReflectionUtil() { } public static Method extractMethod(Object target, String methodName) { final Method[] declaredMethods = target.getClass().getDeclaredMethods(); for (Method method : declaredMethods) { if (method.getName().equals(methodName)) { return method; } } throw new RuntimeException("Method not found: " + methodName); } public static Object getPropertyValue(Object target, String propertyName) { try { final Method getter = extractMethod(target, "get" + StringUtils.capitalize(propertyName)); getter.setAccessible(true); return getter.invoke(target); } catch (Exception e) { throw new RuntimeException("Could not invoke method.", e); } } public static Object invokeMethod(Object target, String methodName, Object... parameters) { try { final Method method = extractMethod(target, methodName); method.setAccessible(true); return method.invoke(target, parameters); } catch (Exception e) { throw new RuntimeException("Could not invoke method.", e); } } public static void setField(String fieldName, Object target, Object value) { final Field field = ReflectionUtils.findField(target.getClass(), fieldName); field.setAccessible(true); ReflectionUtils.setField(field, target, value); } }