om39a
om39a

Reputation: 1406

New object reference for pass by reference in Java

Class 1

private void checkDuplicateCustomer(BulkCustomerVO bulkCustomerVO) {
    PagedDuplicateCustomerVO duplicateCustomerVO = new PagedDuplicateCustomerVO();
    duplicateCustomerVO.setCustomer(bulkCustomerVO.getCustomerVO());
    duplicateCustomerVO = getCustomerBO().getDuplicateCustomerDetails(duplicateCustomerVO);
    if (!MyUtils.isNull(duplicateCustomerVO)) {
        if (duplicateCustomerVO.isValid()) {

             // some operation
            bulkCustomerVO.setErrorDetals(...........)

        }

    }
}

Class 2

public PagedDuplicateCustomerVO getDuplicateCustomerDetails(PagedDuplicateCustomerVO pagedDuplicateCustomer) {
    PagedDuplicateCustomerVO pagedDuplicateCustomerVO = pagedDuplicateCustomer;

        // some operation that changes customerVO reference in pagedDuplicateCustomer

    }
}

In the above scenario, BulkCustomerVO has CustomerVO instance. It is set to PagedDuplicateCustomerVO and passed as argument to getDuplicateCustomerDetails() method where it is getting changed. Those changes affect my flow in checkDuplicateCustomer method.

What I want to do is create a separate customerVO instance from bulkCustomerVO.getCustomerVO() in checkDuplicateCustomer which is specific for the getDuplicateCustomerDetails so any changes in second class wont affect my flow in class 1.

What I can do it copy all the fields from bulkCustomerVO.getCustomerVO() to new CustomerVO, but VO is huge and I dont want to do that. It will be a unwanted code in my class.

so, How can I approach this scenario?

EDIT- I cannot use clone coz this will lead to a over head of changing my VO's to implement cloneable

Upvotes: 0

Views: 235

Answers (3)

om39a
om39a

Reputation: 1406

I have resolved this issue. Bu using clone utiles of SerializationUtils.

duplicateCustomerVO.setCustomer((CustomerVO) SerializationUtils
                .clone(bulkCustomerVO.getCustomerVO()));

Upvotes: 0

plucury
plucury

Reputation: 1120

See http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object, java.lang.Object)

Maybe this is what you want.

==================

public PagedDuplicateCustomerVO getDuplicateCustomerDetails(PagedDuplicateCustomerVO pagedDuplicateCustomer) {

    CustomerVO customer = new CustomerVO();
    BeanUtils.copyProperties(customer, pagedDuplicateCustomer.getCustomerVO());
    pagedDuplicateCustomer.setCustomer(customer);
    return pagedDuplicateCustomer;

}

Upvotes: 3

ejb_guy
ejb_guy

Reputation: 1125

You can try to do the cloning. For this your PagedDuplicateCustomerVO has to implement interface Clonnable interface. Then you can call the clone method on the object to get the shallow clone.

Upvotes: 0

Related Questions