package com.drvijay;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import com.product.base.utils.ObjectUtils;
import com.product.base.utils.ProductConstants;
/**
* @author drvijay
* @date Apr-20-2023 10:30 AM
*/
@SuppressWarnings ( "unused" )
public class UtilHelper
{
private static final long serialVersionUID = 1L;
public static void copy ( Object source, Object target ) throws IllegalArgumentException, IllegalAccessException
{
Class <?> sourceClass = source.getClass ();
Class <?> targetClass = target.getClass ();
Field [] sourceFields = sourceClass.getDeclaredFields ();
Field [] targetFields = targetClass.getDeclaredFields ();
for ( Field sourceField : sourceFields )
{
for ( Field targetField : targetFields )
{
// If the source and target fields have the same name and type
if ( sourceField.getName ().equals ( targetField.getName () ) && sourceField.getType ().equals ( targetField.getType () ) )
{
// Make the source and target field accessible
sourceField.setAccessible ( true );
targetField.setAccessible ( true );
// Copy the value from the source field to the target field
targetField.set ( target, sourceField.get ( source ) );
// Stop looping through the target fields
break;
}
}
}
}
public static void main ( String [] args ) throws Exception
{
// Create a source object
Person sourcePerson = new Person ();
sourcePerson.setFirstName ( "vijay" );
sourcePerson.setLastName ( "kumar" );
sourcePerson.setAge ( 30 );
User u = new User ();
u.setUA ( "ua" );
u.setUB ( "ub" );
List<Address> aList = new ArrayList();
Address address = new Address ();
address.setAddress1 ( "add 1" );
address.setAddress2 ( "add 2" );
address.setPincode ( "54534" );
address.setUser ( u );
aList.add ( address );
address = new Address ();
address.setAddress1 ( "add 11" );
address.setAddress2 ( "add 22" );
address.setPincode ( "545341" );
aList.add ( address );
sourcePerson.setAddressList ( aList );
// Create a target object with similar properties
PersonDTO targetPersonDTO = new PersonDTO ();
// Copy the properties from the source object to the target object
UtilHelper.copy ( sourcePerson, targetPersonDTO );
// Print the values of the target object
System.out.println ( targetPersonDTO.getFirstName () );
System.out.println ( targetPersonDTO.getAge () );
System.out.println ( sourcePerson.toString () );
System.out.println ( targetPersonDTO.toString () );
System.out.println ( targetPersonDTO.getAddressList ().toString () );
}
}