尝试实现可克隆接口
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;
}
}
}
你可以测试这个::
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" );
}
}
}
是的,如果对象类型不同,您可以尝试使用反射,但请记住,属性的名称必须相同
这就是使用反射的答案,使用此类,您可以将所有参数从一个对象传递到另一个对象,无论类型如何,只要方法和属性的名称相同即可。
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() );
}
}