dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java
Expertise: Advanced
Aug 28, 2003

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Override equal() and clone() a Method of an Object

This a very secure and unique way to override equal() and clone() a method of an object.

class MyClass {
    	public boolean equals(MyClass o)
	{		boolean retVal = false;
		if(o == null)
			return retVal;

		if(	!(o instanceof MyClass))
			return retVal;
		try
		{
			java.lang.reflect.Field[] thisF = 
getClass().getDeclaredFields();
			java.lang.reflect.Field[] compareF = 
o.getClass().getDeclaredFields();
			retVal=true;
			for(int i = 0; i <thisF.length ; i++)
			{
				if (!(thisF[i].get(this) == 
compareF[i].get(o)))
				{

					retVal=false;
					break;
				}
			}
		}
		catch(Exception e)
		{
		}
		return retVal;
	}//equals

	public MyClass clone()
	{
		MyClass si =  new MyClass();
		java.lang.reflect.Field[] thisF = getClass().getDeclaredFields();
		java.lang.reflect.Field[] newF =si.getClass().getDeclaredFields();
		for(int i = 0; i <thisF.length ; i++)
		{
			try
			{
			newF[i].set(si,thisF[i].get(this));
			}
			catch(Exception e)
			{
				//ignore
			}
		}
		return si;
	}


}
Supal Chowdhury
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date