Here you can find the source of invokeSetters(final T instance, final Map
Parameter | Description |
---|---|
T | the instance type |
instance | the instance to inject with the variables |
vars | the variables to inject |
Parameter | Description |
---|---|
ReflectiveOperationException | if there was a problem finding or invoking a setter method |
public static <T> T invokeSetters(final T instance, final Map<String, Object> vars) throws ReflectiveOperationException
//package com.java2s; /*/*from w w w .j a v a 2 s.c o m*/ * Copyright 2011 Greg Haines * * 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; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; public class Main { /** * Invoke the setters for the given variables on the given instance. * @param <T> the instance type * @param instance the instance to inject with the variables * @param vars the variables to inject * @return the instance * @throws ReflectiveOperationException if there was a problem finding or invoking a setter method */ public static <T> T invokeSetters(final T instance, final Map<String, Object> vars) throws ReflectiveOperationException { if (instance != null && vars != null) { final Class<?> clazz = instance.getClass(); final Method[] methods = clazz.getMethods(); for (final Entry<String, Object> entry : vars.entrySet()) { final String methodName = "set" + entry.getKey().substring(0, 1).toUpperCase(Locale.US) + entry.getKey().substring(1); boolean found = false; for (final Method method : methods) { if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) { method.invoke(instance, entry.getValue()); found = true; break; } } if (!found) { throw new NoSuchMethodException( "Expected setter named '" + methodName + "' for var '" + entry.getKey() + "'"); } } } return instance; } }