0

I have a class named as order in package com.abc I have another class named as order in different package in different project named as com.bcd

Both order classes have same code get, set functions and variables with no changes.

Then I have objects

com.abc.order obj1 = new com.abc.order();
com.bcd.order obj2 = new com.bdc.order();

Now I have to pass arguments to a function and it takes only obj2 as parameters How can I convert type of obj1 into type of obj2

I cannot change parameters for the function.

Looking forward to your reply. thanks.

3
  • Can you change your abc.Order to extend bcd.Order? (Class names should be upper-case, so use Order instead of order if possible). Commented Apr 9, 2012 at 7:41
  • What's the reason for you code? I think there's a something wrong here. Commented Apr 9, 2012 at 7:50
  • I have a webservice which gets and sets the details, but a part of them have to be moved to EJB so both will have the same classes. If all of the code has to be moved to EJB then a lot of changes are required in the project. Commented Apr 9, 2012 at 8:00

5 Answers 5

1

Have a look at Apache Commons BeanUtils to copy properties from one object to another.

http://commons.apache.org/beanutils/v1.8.3/apidocs/index.html

Something like

BeanUtils.copyProperties(obj2, obj1)

should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

0

You have to copy each field. You can use a BeanIntrospector to help you do this.

Comments

0

You could overload the function, simply by typing it again in your code, but this time so it will take instances of com.abc.order instead. Keep the other one too of course.

If you have defined these two functions, it will work. Problem is duplication. I've never seen a situation like this before and it doesn't sound like good coding practice to duplicate a class and use both in the same code. Can you cast them into each other? like (obj1) obj2? I don't think you can but I'm not 100% sure...

Comments

0

The best solution, if you can is to eliminate one of the two classes especially if they are identical.

Otherwise rename them (first letter capitalised, if possible), again if you can.

Finally, if you cannot perform either of the above, write a conversion method on one or both classes, resolve between the classes where used by retaining their package in all usages.

import com.abc.order;

abc.order obj1 = new abc.order(); 
bcd.order obj2 = new bdc.order();

Comments

0

you can make the class com.bdc.order subclass of com.abc.order

can you clarify why u want to do this ?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.