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


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

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