Monday, December 5, 2011

Class Definition » Class Object

Getting java.lang.Class: Information about your object
public class MainClass {
  public static void main(String[] a) {
    String country = "Canada";
    Class myClass = country.getClass();
    System.out.println(myClass.getName());
  }
}
output
java.lang.String
 
 
Comparing Objects 
public class MainClass {
  public static void main(String[] args) {
    Employee emp1 = new Employee("M""A");
    Employee emp2 = new Employee("M""A");
    if (emp1.equals(emp2))
      System.out.println("These employees are the same.");
    else
      System.out.println("These are different employees.");
  }
}

class Employee {
  private String lastName;

  private String firstName;

  public Employee(String lastName, String firstName) {
    this.lastName = lastName;
    this.firstName = firstName;
  }

  public String getLastName() {
    return this.lastName;
  }

  public String getFirstName() {
    return this.firstName;
  }

  public boolean equals(Object obj)

  {
    if (this == obj)
      return true;
    if (this == null)
      return false;

    if (this.getClass() != obj.getClass())
      return false;

    Employee emp = (Employeeobj;
    return this.lastName.equals(emp.getLastName()) &&  
this.firstName.equals(emp.getFirstName());
  }
}

Implement equals method using commons-lang
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;

import java.io.Serializable;

public class Main implements Serializable {
  private Long id;

  private String title;

  private String author;

  public boolean equals(Object object) {
    if (!(object instanceof Main)) {
      return false;
    }

    if (object == this) {
      return true;
    }

    Main book = (Mainobject;
    return new EqualsBuilder().append(this.id, book.id).append
 (this.title, book.title).append(
        this.author, book.author).isEquals();

    // return EqualsBuilder.reflectionEquals(this, book);

  }
}

  




No comments:

Post a Comment