Here you can find the source of setFieldValues(Object bean, Map
Parameter | Description |
---|---|
bean | a parameter |
valMap | a parameter |
public static void setFieldValues(Object bean, Map<String, Object> valMap)
//package com.java2s; /*//from w ww .j a va 2s . c om * Copyright (C) 2013 The Open Source Project By Yunying.Zhang * * 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. * author:Yunying.Zhang * date:2013-09-27 */ import java.lang.reflect.Field; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class Main { /** * Set all fields' value. * * @param bean * @param valMap */ public static void setFieldValues(Object bean, Map<String, Object> valMap) { Class<?> cls = bean.getClass(); Map<String, Field> fieldMap = getFields(cls); Iterator<Entry<String, Object>> iterator = valMap.entrySet().iterator(); while (iterator.hasNext()) { try { Field field = fieldMap.get(iterator.next().getKey()); if (field == null) { continue; } field.setAccessible(true); field.set(bean, valMap.get(field.getName())); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } /** * Get all fields, contain superclass' fields. * @param cls * @return */ public static Map<String, Field> getFields(Class<?> cls) { Map<String, Field> fieldMap = new HashMap<String, Field>(); Class<?> superClass = cls.getSuperclass(); if (superClass != null) { fieldMap.putAll(getFields(superClass)); } Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { fieldMap.put(field.getName(), field); } return fieldMap; } }