java.lang.reflect.Field.equals() Method Example



Description

The java.lang.reflect.Field.equals(Object obj) method compares this Field against the specified object. Returns true if the objects are the same. Two Field objects are the same if they were declared by the same class and have the same name and type.

Declaration

Following is the declaration for java.lang.reflect.Field.equals(Object obj) method.

public boolean equals(Object obj)

Parameters

obj − the object to compare.

Returns

true if this object is the same as the obj argument; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Field.equals(Object obj) method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) {

      Field[] fields = SampleClass.class.getDeclaredFields();
      boolean isEquals = fields[0].equals(fields[1]);
      System.out.println("Fields are " + (isEquals?"equal.":"not equal."));
   }
}

@CustomAnnotation(name = "SampleClass",  value = "Sample Class Annotation")
class SampleClass {

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   private String sampleField;
   private String sampleField1;
  
   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   }

   public String getSampleField1() {
      return sampleField1;
   }

   public void setSampleField1(String sampleField1) {
      this.sampleField1 = sampleField1;
   } 
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
   public String name();
   public String value();
}

Let us compile and run the above program, this will produce the following result −

Fields are not equal.
java_reflect_field.htm
Advertisements