クラス属性に値を割り当てる

2068 ワード

古いオブジェクトの同じ名前のプロパティ値を新しいオブジェクトのNULL以外のプロパティ値で置き換える共通の方法を書きました.

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		User user1 = new User();
		User user2 = new User();
		user2.setAge(222);
		user2.setNum(333);
		user2.setUserName("222Name");
		User user = (User) replaceValue(user1, user2);
		System.out.println(user.toString());
		
	}
	
    public static String generateSetName(String fieldName) {  
        if (null == fieldName || "".equals(fieldName)) {  
            return null;  
        }  
        return "set" + fieldName.substring(0, 1).toUpperCase()  
                + fieldName.substring(1);  
    } 
	
	private static Object replaceValue(Object newObject, Object oldObject)
	{
		try
		{
			Field[] incrementFields = newObject.getClass().getDeclaredFields();
			Field[] oldFields = oldObject.getClass().getDeclaredFields();
			for (int i = 0; i < incrementFields.length; i++)
			{
				Field incrementField = incrementFields[i];
				incrementField.setAccessible(true);
				for (int j = 0; j < oldFields.length; j++)
				{
					Field field = incrementFields[j];
					field.setAccessible(true);
					if (incrementField.getName().equals(field.getName()))
					{
						if(incrementField.get(newObject) != null)
						{
							Method fieldSetMet = newObject.getClass()  
							.getMethod(generateSetName(incrementField.getName()), incrementField.getType());  
								fieldSetMet.invoke(oldObject, incrementField.get(newObject));
						}
							
					}
				}
			}
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return oldObject;

	}
	
	

}