Here you can find the source of setFieldIfExists(final Object instance, final String fieldName, final Object value)
public static boolean setFieldIfExists(final Object instance, final String fieldName, final Object value)
//package com.java2s; import java.lang.reflect.*; public class Main { public static boolean setFieldIfExists(final Object instance, final String fieldName, final Object value) { try {//from w w w. j av a 2s . c o m final Field f = instance.getClass().getField(fieldName); if (value instanceof Boolean || f.getType().isInstance(value)) { f.set(instance, value); return true; } else { System.out.println(instance.getClass() + " '" + fieldName + "' field not assignable with " + value.getClass() + ", it's a: " + f.getType()); } } catch (final IllegalAccessException ex) { throw new RuntimeException(ex); } catch (final NoSuchFieldException nsfe) { // OK - throw new RuntimeException(instance.getClass()+" has no '"+fieldName+"' field", nsfe); } return false; } }