Refresh Your Java - Before Java Interview
We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....
Copy Primitive Bean Properties , PropertyUtils, BeanMap
The following class copies only Privimitive
Data types or the Wrapper
classes , and ignores Custom
Value Objects.
import java.util.Arrays;
import java.util.Calendar;
import
java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
public class PrimitivePropertyCopier {
private static
final HashSet<Class<?>> WRAPPER_TYPES
= getWrapperTypes();
private static Logger log
= Logger.getLogger(RequestTranslatorUtil.class);
public static void copyNonMemberClassProperties (Object
target, Object source) {
BeanMap
beanMapPojo = new BeanMap( target );
BeanMap beanMap = new BeanMap( source );
Set keys =
beanMapPojo.keySet( );
Iterator keyIterator =
keys.iterator( );
while(
keyIterator.hasNext( ) ) {
try {
String
propertyName = (String) keyIterator.next( );
Class classType = beanMap.getType(propertyName);
if (classType != null &&
(isWrapperType(classType)||
classType.isPrimitive()))
{
if ( PropertyUtils.isWriteable(target, propertyName)) {
try
{
Object
value = beanMap.get( propertyName );
if
(value != null) {
PropertyUtils.setProperty(target, propertyName, value);
}
}
catch (Exception e) {
//
No need to worry about this , we can ignore.
log.error("Could
be Ignored " + e.getMessage());
}
}
}
} catch (Exception e) {
log.error("Could
be Ignored " + e.getMessage());
}
}
}
/**
* This method checks the Type
Of Variable if that is Copyable or not.
*
* @param clazz
*
@return
*/
public static
boolean isWrapperType(Class<?> clazz)
{
return WRAPPER_TYPES.contains(clazz);
}
private static
HashSet<Class<?>>
getWrapperTypes()
{
HashSet<Class<?>> ret = new
HashSet<Class<?>>();
ret.add(String.class);
ret.add(Boolean.class);
ret.add(Character.class);
ret.add(Byte.class);
ret.add(Short.class);
ret.add(Integer.class);
ret.add(Long.class);
ret.add(Float.class);
ret.add(Double.class);
ret.add(Void.class);
ret.add(Calendar.class);
return ret;
}
}
This Portal is intended to put all Java/J2ee related topics at one single place for quick referance, not only Technical , but also the Project Management Related thing such as Development Process methodoogies build process, unit testing etc.,
This Portal has More than 500 Java Interview Questions (also could be Considered as Quick Notes) very neatly separated topic by topic with simple diagrams which makes you easily understandable. Importantly these are from our Realtime expericance.