Search This Blog

Showing posts with label dynamic. Show all posts
Showing posts with label dynamic. Show all posts

Monday, April 24, 2023

Java Sample - Copy any object into any object including sub object fields generic

 Steps 1:

Source

Person.java(list address)

Address.java(User.java)


public class Person implements Serializable

{

private String firstName;

private String lastName;

private int age;

private List <Address> addressList;

}

public class Address implements Serializable

{

private int id;

private String address1;

private String address2;

private String city;

private String state;

private String country;

private String pincode;

private String contactNumber;

private String email;

private User user;

}




Target

PersonDTO.java (list addressDTO)

AddressDTO.java (User.java)

public class PersonDTO implements Serializable

{

private String firstName;

private int age;

private String lastName;

private List <AddressDTO> addressList;

}

public class AddressDTO implements Serializable

{

private int id;

private String address1;

private String address2;

private String city;

private String state;

private String country;

private String pincode;

private String contactNumber;

private String email;

private User user;

}


Step 2: Sample java class

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 () );

}

}



Output


vijay

30

Person(firstName=vijay, lastName=kumar, age=30, addressList=[Address(id=0, address1=add 1, address2=add 2, city=null, state=null, country=null, pincode=54534, contactNumber=null, email=null, user=User(uA=ua, uB=ub)), Address(id=0, address1=add 11, address2=add 22, city=null, state=null, country=null, pincode=545341, contactNumber=null, email=null, user=null)])

PersonDTO(firstName=vijay, age=30, lastName=kumar, addressList=[Address(id=0, address1=add 1, address2=add 2, city=null, state=null, country=null, pincode=54534, contactNumber=null, email=null, user=User(uA=ua, uB=ub)), Address(id=0, address1=add 11, address2=add 22, city=null, state=null, country=null, pincode=545341, contactNumber=null, email=null, user=null)])

[Address(id=0, address1=add 1, address2=add 2, city=null, state=null, country=null, pincode=54534, contactNumber=null, email=null, user=User(uA=ua, uB=ub)), Address(id=0, address1=add 11, address2=add 22, city=null, state=null, country=null, pincode=545341, contactNumber=null, email=null, user=null)]


Tuesday, July 9, 2019

Python - Construct Json in loop

data={}
for  weightagesObj in weightagesAllObject:
        item = {"weight":weightagesObj.weight, "rank":weightagesObj.rank}
        data[weightagesObj.scrip] = item
nseJson=json.loads ( json.dumps(data) )
print ( nseJson["scrip name"] )



{
"RELIANCE": {
"weightage": 9.04,
"rank": 1
},
"TATAMOTORS": {
"weightage": 9.01,
"rank": 2
}
}

Friday, November 16, 2018

Java Dynamic Method Call with params by using reflection

package com.product.rpa.api.ws;

import java.lang.reflect.Method;

public class DynamicMethodCall
{
public String sample ()
{
return "vijay";
}

public String sampleWithParam ( String x )
{
return x + " " + x;
}

public String sampleWithMultipleParams ( String x, int i )
{
return x + " " + i;
}

public static void main ( String args[] ) throws Exception
{
DynamicMethodCall dynamicMethodCall = new DynamicMethodCall ();

// with out param
Method method = dynamicMethodCall.getClass ().getMethod ( "sample" );
String result = (String) method.invoke ( dynamicMethodCall );
System.out.println ( result );

// with param
// String parameter
Class [] paramString = new Class[1];
paramString[0] = String.class;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithParam", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - param" );
System.out.println ( result );

// with multiple params
// String parameter
paramString = new Class[2];
paramString[0] = String.class;
paramString[1] = Integer.TYPE;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithMultipleParams", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - ", 100 );
System.out.println ( result );

}
}

Wednesday, June 14, 2017

Dynamic Web Module 3.0 requires Java 1.6 or newer” in Maven Projects

Open your project’s pom.xml and add this plugin tag
<build>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
    </plugins>
</build>
Finally, right click on your project > Maven > Update Project

Tuesday, November 8, 2016

How to fetch from list of nested list- Dynamic Loop

Assume the bean is like below, CommentsBean has CommentsBeanlist.

public class CommentsBean {

int id;
int parentId;
String msg;
List commentsBeanList;

public CommentsBean() {

}

public CommentsBean(int id, int parentId, String msg) {
super();
this.id = id;
this.parentId = parentId;
this.msg = msg;
}

@Override
public String toString() {
return "CommentsBean [id=" + id + ", parentId=" + parentId + ", msg=" + msg + ", commentsBeanList="
+ commentsBeanList + "]";
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getParentId() {
return parentId;
}

public void setParentId(int parentId) {
this.parentId = parentId;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public List getCommentsBeanList() {
return commentsBeanList;
}

public void setCommentsBeanList(List commentsBeanList) {
this.commentsBeanList = commentsBeanList;
}


}


Program to extract that dynamically.

public class DynamicListLoop {

public static void main(String[] args) {
List commntsBeanList = new ArrayList<>();
List commntsBeanChildList1 = new ArrayList<>();
List commntsBeanChildList11 = new ArrayList<>();
CommentsBean commentsBeanchild20 = new CommentsBean(4,-1, "second");
CommentsBean commentsBeanchild21 = new CommentsBean(5,4, "second-child-1");
commntsBeanChildList11.add(commentsBeanchild20);
commntsBeanChildList11.add(commentsBeanchild21);
CommentsBean commentsBeanchild2 = new CommentsBean(3,2, "first-child-2");
CommentsBean commentsBeanchild = new CommentsBean(2,1, "first-child-1");
commentsBeanchild.setCommentsBeanList(commntsBeanChildList11);
commntsBeanChildList1.add(commentsBeanchild);
commntsBeanChildList1.add(commentsBeanchild2);
CommentsBean commentsBean = new CommentsBean(1,-1, "first");
commentsBean.setCommentsBeanList(commntsBeanChildList1);
commntsBeanList.add(commentsBean);
System.out.println(commntsBeanList.toString());
//write a function and pass the parent bean list.
commentsBeanParseInLoop (commntsBeanList );

}
public static void commentsBeanParseInLoop ( List commntsBeanList )
{
if ( commntsBeanList!=null && commntsBeanList.size() > 0 )
{
for ( CommentsBean cb : commntsBeanList )
{
System.out.println(cb.getId() + " : " + cb.getMsg() );
if ( cb.getCommentsBeanList() !=null && cb.getCommentsBeanList().size() > 0 )
{
//call the same function and pass the inner bean list
commentsBeanParseInLoop ( cb.getCommentsBeanList() );
}
}
}
}

}

Hit Counter


View My Stats