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



Description

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

Declaration

Following is the declaration for java.lang.reflect.Constructor.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.Constructor.equals(Object obj) method.

package com.tutorialspoint;

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

public class ConstructorDemo {

   public static void main(String[] args) {

      Constructor[] constructors = SampleClass.class.getConstructors();
      boolean isEquals = constructors[0].equals(constructors[1]);
      System.out.println("Constructors are " + (isEquals?"equal.":"not equal."));
   }
}

@CustomAnnotation(name = "SampleClass",  value = "Sample Class Annotation")
class SampleClass {
   private String sampleField;

   @CustomAnnotation(name="sampleClassConstructor",  value = "Sample Constructor Annotation")
   public SampleClass(){
   }

   public SampleClass(String sampleField){
      this.sampleField = sampleField;
   }

   public String getSampleField() {
      return sampleField;
   }

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

@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 −

Constructors are not equal.
java_reflect_constructor.htm
Advertisements