Creates a copy of a new object based on the parameters of the specified method and returns

Source: Internet
Author: User

/**
* Construct a copy of a new object based on the parameters of the specified method and return it
* @ Param OBJ original object
* @ Return new object
* @ Throws nosuchmethodexception
* @ Throws invocationtargetexception
* @ Throws illegalaccessexception
* @ Throws instantiationexception
* @ Throws securityexception
* @ Throws illegalargumentexception
*/
@ Suppresswarnings ("unchecked ")
Public static object copy (Object OBJ) throws illegalargumentexception, securityexception, instantiationexception, illegalaccessexception,
Invocationtargetexception, nosuchmethodexception
{
// Obtain the object type
Class classtype = obj. getclass ();

// Create a new object using the default constructor. The getconstructor determines which constructor is called based on its parameters.
Object objectcopy = classtype. getconstructor (new class [] {}). newinstance (new object [] {});

// Obtain all attributes of an object
Field [] fields = classtype. getdeclaredfields ();

For (INT I = 0; I <fields. length; I ++)
{
// Obtain the corresponding attribute in the array
Field field = Fields [I];

String fieldname = field. getname ();
String stringletter = fieldname. substring (0, 1). touppercase ();

// Obtain the getxxx and setxxx method names of the corresponding attributes.
String getname = "get" + stringletter + fieldname. substring (1 );
String setname = "set" + stringletter + fieldname. substring (1 );

// Obtain the corresponding method
Method getmethod = classtype. getmethod (getname, new class [] {});
Method setmethod = classtype. getmethod (setname, new class [] {field. GetType ()});

// Call the getxxx () method of the source object
Object value = getmethod. Invoke (OBJ, new object [] {});

// Call the setxxx () method of the copy object
Setmethod. Invoke (objectcopy, new object [] {value });
}

Return objectcopy;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.