Try to implement cloneable interface
public class SomeType implements Cloneable {
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public Object clone() {
try {
return super.clone();
} catch(CloneNotSupportedException e) {
System.out.println("Cloning not allowed.");
return this;
}
}
}
and you can test this::
public class Test {
public static void main (String args[]) {
SomeType a = new SomeType();
SomeType b = (SomeType) a.clone();
if ( a == b ) {
System.out.println( "yes" );
} else {
System.out.println( "no" );
}
}
}
yes, you can try with reflection if the object types are different, but keep in mind that the names of the attributes must be equal
and this is the answer using reflection, with this class you can pass all the parameters from one object to another, regardless of type as long as the names of methods and attributes are the same.
package co.com;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SetAttributes {
public static String capitalize( String word ) {
return Character.toUpperCase( word.charAt( 0 ) ) + word.substring( 1 );
}
public static void setAttributes( Object from, Object to ) {
Field [] fieldsFrom = from.getClass().getDeclaredFields();
Field [] fielsdTo = to.getClass().getDeclaredFields();
for (Field fieldFrom: fieldsFrom) {
for (Field fieldTo: fielsdTo) {
if ( fieldFrom.getName().equals( fieldTo.getName() ) ) {
try {
Method [] methodsTo = to.getClass().getDeclaredMethods();
for ( Method methodTo: methodsTo ) {
if ( methodTo.getName().equals( "set" + capitalize( capitalize( fieldTo.getName() ) ) ) ) {
Method methodFrom = from.getClass().getDeclaredMethod( "get" + capitalize( fieldFrom.getName() ), null );
methodTo.invoke(to, methodFrom.invoke( from, null ) );
break;
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
System.err.println( fieldFrom );
}
}
}
public static void main (String args[]) {
SomeType a = new SomeType();
SomeType b = new SomeType();
a.setA( "This" );
setAttributes( a, b );
System.err.println( b.getA() );
}
}