java.lang.reflect - Quick Guide


Advertisements


java.lang.reflect - AccessibleObject

Introduction

The java.lang.reflect.AccessibleObject class is the base class for Field, Method and Constructor objects. It provides the ability to flag a reflected object as suppressing default Java language access control checks when it is used. The access checks--for public, default (package) access, protected, and private members--are performed when Fields, Methods or Constructors are used to set or get fields, to invoke methods, or to create and initialize new instances of classes, respectively. Setting the accessible flag in a reflected object permits sophisticated applications with sufficient privilege, such as Java Object Serialization or other persistence mechanisms, to manipulate objects in a manner that would normally be prohibited.

Class declaration

Following is the declaration for java.lang.reflect.AccessibleObject class −

public class AccessibleObject
   extends Object
      implements AnnotatedElement

Constructors

S.N. Constructor & Description
1 protected AccessibleObject()

Constructor: only used by the Java Virtual Machine.

Class methods

S.N. Method & Description
1 <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.

2 Annotation[] getAnnotations()

Returns all annotations present on this element.

3 Annotation[] getDeclaredAnnotations()

Returns all annotations that are directly present on this element.

4 boolean isAccessible()

Get the value of the accessible flag for this object.

5 boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)

Returns true if an annotation for the specified type is present on this element, else false.

6 static void setAccessible(AccessibleObject[] array, boolean flag)

Convenience method to set the accessible flag for an array of objects with a single security check (for efficiency).

7 void setAccessible(boolean flag)

Set the accessible flag for this object to the indicated boolean value.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.lang.reflect.AccessibleObject.getAnnotation(Class annotationClass) Method Example

Description

The java.lang.reflect.AccessibleObject.getAnnotation(Class annotationClass) method returns this element's annotation for the specified type if such an annotation is present, else null.

Declaration

Following is the declaration for java.lang.reflect.AccessibleObject.getAnnotation(Class annotationClass) method.

public  T getAnnotation(Class annotationClass)

Parameters

  • annotationClass - the Class object corresponding to the annotation type.

Return Value

this element's annotation for the specified annotation type if present on this element, else null.

Exceptions

  • NullPointerException - if the given annotation class is null.

Example

The following example shows the usage of java.lang.reflect.AccessibleObject.getAnnotation(Class annotationClass) method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleMethod = SampleClass.class.getMethod("sampleMethod");

      Annotation annotation = sampleMethod.getAnnotation(CustomAnnotation.class);
      if(annotation instanceof CustomAnnotation){
         CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
         System.out.println("name: " + customAnnotation.name());
         System.out.println("value: " + customAnnotation.value());
      }
   }
}

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

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   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 −

name: sampleMethod
value: Sample Method Annotation

java.lang.reflect.AccessibleObject.getAnnotations() Method Example

Description

The java.lang.reflect.AccessibleObject.getAnnotations() method returns all annotations present on this element. (Returns an array of length zero if this element has no annotations.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.AccessibleObject.getAnnotations() method.

public Annotation[] getAnnotations()

Return Value

all annotations present on this element.

Example

The following example shows the usage of java.lang.reflect.AccessibleObject.getAnnotations() method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleMethod = SampleClass.class.getMethod("sampleMethod");

      Annotation[] annotations = sampleMethod.getAnnotations();

      for(Annotation annotation : annotations){
         if(annotation instanceof CustomAnnotation){
            CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
            System.out.println("name: " + customAnnotation.name());
            System.out.println("value: " + customAnnotation.value());
         }
      }
   }
}

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

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   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 −

name: sampleMethod
value: Sample Method Annotation

java.lang.reflect.AccessibleObject.getDeclaredAnnotations() Method Example

Description

The java.lang.reflect.AccessibleObject.getDeclaredAnnotations() method returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.AccessibleObject.getDeclaredAnnotations() method.

public Annotation[] getDeclaredAnnotations()

Return Value

all annotations directly present on this element.

Example

The following example shows the usage of java.lang.reflect.AccessibleObject.getDeclaredAnnotations() method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleMethod = SampleClass.class.getMethod("sampleMethod");

      Annotation[] annotations = sampleMethod.getDeclaredAnnotations();

      for(Annotation annotation : annotations){
         if(annotation instanceof CustomAnnotation){
            CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
            System.out.println("name: " + customAnnotation.name());
            System.out.println("value: " + customAnnotation.value());
         }
      }
   }
}

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

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   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 −

name: sampleMethod
value: Sample Method Annotation

java.lang.reflect.AccessibleObject.isAccessible() Method Example

Description

The java.lang.reflect.AccessibleObject.isAccessible() method gets the value of the accessible flag for this object.

Declaration

Following is the declaration for java.lang.reflect.AccessibleObject.isAccessible() method.

public boolean isAccessible()

Return Value

the value of the object's accessible flag.

Example

The following example shows the usage of java.lang.reflect.AccessibleObject.isAccessible() method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
         AccessibleObject sampleField = SampleClass.class.getDeclaredField("sampleField");
         System.out.println("sampleField.isAccessible: " + sampleField.isAccessible());
   }
}

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

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   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 −

sampleField.isAccessible: false

java.lang.reflect.AccessibleObject.isAnnotationPresent(Class<? extends Annotation> annotationClass) Method Example

Description

The java.lang.reflect.AccessibleObject.isAnnotationPresent(Class<? extends Annotation> annotationClass) method returns true if an annotation for the specified type is present on this element, else false.

Declaration

Following is the declaration for java.lang.reflect.AccessibleObject.isAnnotationPresent(Class<? extends Annotation> annotationClass) method.

public boolean isAnnotationPresent(Class<? extends Annotation>  annotationClass)

Parameters

  • annotationClass - the Class object corresponding to the annotation type.

Return Value

true if an annotation for the specified annotation type is present on this element, else false.

Exceptions

  • NullPointerException - if the given annotation class is null.

Example

The following example shows the usage of java.lang.reflect.AccessibleObject.isAnnotationPresent(Class<? extends Annotation> annotationClass) method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleMethod = SampleClass.class.getMethod("sampleMethod");
      System.out.println("sampleMethod.isAnnotationPresent: " 
         + sampleMethod.isAnnotationPresent(CustomAnnotation.class));
   }
}

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

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   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 −

sampleMethod.isAnnotationPresent: true

java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject[] array, boolean flag) Method Example

Description

The java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject[] array, boolean flag) method is a convenience method to set the accessible flag for an array of objects with a single security check (for efficiency).

Declaration

Following is the declaration for java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject[] array, boolean flag) method.

public static void setAccessible(AccessibleObject[] array, boolean flag) 
   throws SecurityException

Parameters

  • array - the array of AccessibleObjects.

  • flag - the new value for the accessible flag in each object.

Exceptions

  • SecurityException - if the request is denied.

Example

The following example shows the usage of java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject[] array, boolean flag) method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleField = SampleClass.class.getDeclaredField("sampleField");
      System.out.println("sampleField.isAccessible: " + sampleField.isAccessible());

      AccessibleObject[] array = new AccessibleObject[1];
      array[0] = sampleField;

      AccessibleObject.setAccessible(array, true);
      System.out.println("sampleField.isAccessible: " + sampleField.isAccessible());
   }
}

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

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   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 −

sampleField.isAccessible: false
sampleField.isAccessible: true

java.lang.reflect.AccessibleObject.setAccessible(boolean flag) Method Example

Description

The java.lang.reflect.AccessibleObject.setAccessible(boolean flag) method sets the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.

Declaration

Following is the declaration for java.lang.reflect.AccessibleObject.setAccessible(boolean flag) method.

public void setAccessible(boolean flag)
   throws SecurityException

Parameters

  • flag - the new value for the accessible flag in each object.

Exceptions

  • SecurityException - if the request is denied.

Example

The following example shows the usage of java.lang.reflect.AccessibleObject.setAccessible(boolean flag) method.

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;

public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleField = SampleClass.class.getDeclaredField("sampleField");
      System.out.println("sampleField.isAccessible: " + sampleField.isAccessible());
      sampleField.setAccessible(true);
      System.out.println("sampleField.isAccessible: " + sampleField.isAccessible());
   }
}

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

   @CustomAnnotation(name="sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }

   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 −

sampleField.isAccessible: false
sampleField.isAccessible: true

java.lang.reflect - Array

Introduction

The java.lang.reflect.Array class provides static methods to dynamically create and access Java arrays. Array permits widening conversions to occur during a get or set operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

Class declaration

Following is the declaration for java.lang.reflect.Array class −

public final class Array
   extends Object

Class methods

S.N. Method & Description
1 static Object get(Object array, int index)

Returns the value of the indexed component in the specified array object.

2 static boolean getBoolean(Object array, int index)

Returns the value of the indexed component in the specified array object, as a boolean.

3 static byte getByte(Object array, int index)

Returns the value of the indexed component in the specified array object, as a byte.

4 static char getChar(Object array, int index)

Returns the value of the indexed component in the specified array object, as a char.

5 static double getDouble(Object array, int index)

Returns the value of the indexed component in the specified array object, as a double.

6 static float getFloat(Object array, int index)

Returns the value of the indexed component in the specified array object, as a float.

7 static int getInt(Object array, int index)

Returns the value of the indexed component in the specified array object, as an int.

8 static int getLength(Object array)

Returns the length of the specified array object, as an int.

9 static long getLong(Object array, int index)

Returns the value of the indexed component in the specified array object, as a long.

10 static short getShort(Object array, int index)

Returns the value of the indexed component in the specified array object, as a short.

11 static Object newInstance(Class<?> componentType, int... dimensions)

Creates a new array with the specified component type and dimensions.

12 static Object newInstance(Class<?> componentType, int length)

Creates a new array with the specified component type and length.

13 static void set(Object array, int index, Object value)

Sets the value of the indexed component of the specified array object to the specified new value.

14 static void setBoolean(Object array, int index, boolean z)

Sets the value of the indexed component of the specified array object to the specified boolean value.

15 static void setByte(Object array, int index, byte b)

Sets the value of the indexed component of the specified array object to the specified byte value.

16 static void setChar(Object array, int index, char c)

Sets the value of the indexed component of the specified array object to the specified char value.

17 static void setDouble(Object array, int index, double d)

Sets the value of the indexed component of the specified array object to the specified double value.

18 static void setFloat(Object array, int index, float f)

Sets the value of the indexed component of the specified array object to the specified float value.

19 static void setInt(Object array, int index, int i)

Sets the value of the indexed component of the specified array object to the specified int value.

20 static void setLong(Object array, int index, long l)

Sets the value of the indexed component of the specified array object to the specified long value.

21 static void setShort(Object array, int index, short s)

Sets the value of the indexed component of the specified array object to the specified short value.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.lang.reflect.Array.get(Object array, int index) Method Example

Description

The java.lang.reflect.Array.get(Object array, int index) method returns the value of the indexed component in the specified array object. The value is automatically wrapped in an object if it has a primitive type.

Declaration

Following is the declaration for java.lang.reflect.Array.get(Object array, int index) method.

public static Object get(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.get(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      String[] stringArray = (String[]) Array.newInstance(String.class, 3);

      Array.set(stringArray, 0, "Mahesh");
      Array.set(stringArray, 1, "Ramesh");
      Array.set(stringArray, 2, "Suresh");

      System.out.println("stringArray[0] = " + Array.get(stringArray, 0));
      System.out.println("stringArray[1] = " + Array.get(stringArray, 1));
      System.out.println("stringArray[2] = " + Array.get(stringArray, 2));
   }
}

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

stringArray[0] = Mahesh
stringArray[1] = Ramesh
stringArray[2] = Suresh

java.lang.reflect.Array.getBoolean(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getBoolean(Object array, int index) method returns the value of the indexed component in the specified array object, as a boolean.

Declaration

Following is the declaration for java.lang.reflect.Array.getBoolean(Object array, int index) method.

public static boolean getBoolean(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getBoolean(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      boolean[] array = (boolean[]) Array.newInstance(boolean.class, 3);

      Array.set(array, 0, false);
      Array.set(array, 1, true);
      Array.set(array, 2, true);

      System.out.println("array[0] = " + Array.getBoolean(array, 0));
      System.out.println("array[1] = " + Array.getBoolean(array, 1));
      System.out.println("array[2] = " + Array.getBoolean(array, 2));
   }
}

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

array[0] = false
array[1] = true
array[2] = true

java.lang.reflect.Array.getByte(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getByte(Object array, int index) method returns the value of the indexed component in the specified array object, as a byte.

Declaration

Following is the declaration for java.lang.reflect.Array.getByte(Object array, int index) method.

public static byte getByte(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getByte(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      byte[] array = new byte[]{1,2,3};

      System.out.println("array[0] = " + Array.getByte(array, 0));
      System.out.println("array[1] = " + Array.getByte(array, 1));
      System.out.println("array[2] = " + Array.getByte(array, 2));
   }
}

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

array[0] = 1
array[1] = 2
array[2] = 3

java.lang.reflect.Array.getChar(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getChar(Object array, int index) method returns the value of the indexed component in the specified array object, as a char.

Declaration

Following is the declaration for java.lang.reflect.Array.getChar(Object array, int index) method.

public static byte getChar(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getChar(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      char[] array = new char[]{'1','2','3'};

      System.out.println("array[0] = " + Array.getChar(array, 0));
      System.out.println("array[1] = " + Array.getChar(array, 1));
      System.out.println("array[2] = " + Array.getChar(array, 2));
   }
}

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

array[0] = 1
array[1] = 2
array[2] = 3

java.lang.reflect.Array.getDouble(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getDouble(Object array, int index) method returns the value of the indexed component in the specified array object, as a double.

Declaration

Following is the declaration for java.lang.reflect.Array.getDouble(Object array, int index) method.

public static double getDouble(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getDouble(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      double[] array = new double[]{1.0,2.0,3.0};
      System.out.println("array[0] = " + Array.getDouble(array, 0));
      System.out.println("array[1] = " + Array.getDouble(array, 1));
      System.out.println("array[2] = " + Array.getDouble(array, 2));
   }
}

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

array[0] = 1.0
array[1] = 2.0
array[2] = 3.0

java.lang.reflect.Array.getFloat(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getFloat(Object array, int index) method returns the value of the indexed component in the specified array object, as a float.

Declaration

Following is the declaration for java.lang.reflect.Array.getFloat(Object array, int index) method.

public static float getFloat(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getFloat(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      float[] array = new float[]{1.0f,2.0f,3.0f};

      System.out.println("array[0] = " + Array.getFloat(array, 0));
      System.out.println("array[1] = " + Array.getFloat(array, 1));
      System.out.println("array[2] = " + Array.getFloat(array, 2));
   }
}

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

array[0] = 1.0
array[1] = 2.0
array[2] = 3.0

java.lang.reflect.Array.getInt(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getInt(Object array, int index) method returns the value of the indexed component in the specified array object, as a int.

Declaration

Following is the declaration for java.lang.reflect.Array.getInt(Object array, int index) method.

public static int getInt(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getInt(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      int[] array = new int[]{1,2,3};

      System.out.println("array[0] = " + Array.getInt(array, 0));
      System.out.println("array[1] = " + Array.getInt(array, 1));
      System.out.println("array[2] = " + Array.getInt(array, 2));
   }
}

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

array[0] = 1
array[1] = 2
array[2] = 3

java.lang.reflect.Array.getLength(Object array) Method Example

Description

The java.lang.reflect.Array.getLength(Object array) method returns the length of the specified array object, as an int.

Declaration

Following is the declaration for java.lang.reflect.Array.getLength(Object array) method.

public static int getLength(Object array)
   throws IllegalArgumentException

Parameters

  • array - the array.

Return Value

the length of the array.

Exceptions

  • IllegalArgumentException - If the specified object is not an array.

Example

The following example shows the usage of java.lang.reflect.Array.getLength(Object array) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      int[] array = new int[]{1,2,3};

      System.out.println("array length = " + Array.getLength(array));
   }
}

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

array length = 3

java.lang.reflect.Array.getLong(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getLong(Object array, int index) method returns the value of the indexed component in the specified array object, as a long.

Declaration

Following is the declaration for java.lang.reflect.Array.getLong(Object array, int index) method.

public static long getLong(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getLong(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      long[] array = new long[]{1,2,3};

      System.out.println("array[0] = " + Array.getLong(array, 0));
      System.out.println("array[1] = " + Array.getLong(array, 1));
      System.out.println("array[2] = " + Array.getLong(array, 2));
   }
}

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

array[0] = 1
array[1] = 2
array[2] = 3

java.lang.reflect.Array.getShort(Object array, int index) Method Example

Description

The java.lang.reflect.Array.getShort(Object array, int index) method returns the value of the indexed component in the specified array object, as a short.

Declaration

Following is the declaration for java.lang.reflect.Array.getShort(Object array, int index) method.

public static short getShort(Object array, int index)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

Return Value

the (possibly wrapped) value of the indexed component in the specified array.

Exceptions

  • NullPointerException - If the specified object is null.

  • IllegalArgumentException - If the specified object is not an array.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array.

Example

The following example shows the usage of java.lang.reflect.Array.getShort(Object array, int index) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      short[] array = new short[]{1,2,3};

      System.out.println("array[0] = " + Array.getShort(array, 0));
      System.out.println("array[1] = " + Array.getShort(array, 1));
      System.out.println("array[2] = " + Array.getShort(array, 2));
   }
}

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

array[0] = 1
array[1] = 2
array[2] = 3

java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) Method Example

Description

The java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) method creates a new array with the specified component type and dimensions. If componentType represents a non-array class or interface, the new array has dimensions.length dimensions and componentType as its component type. If componentType represents an array class, the number of dimensions of the new array is equal to the sum of dimensions.length and the number of dimensions of componentType. In this case, the component type of the new array is the component type of componentType.

Declaration

Following is the declaration for java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) method.

public static Object newInstance(Class<?> componentType, int... dimensions)
   throws IllegalArgumentException, NegativeArraySizeException

Parameters

  • componentType - the Class object representing the component type of the new array.

  • dimensions - an array of int representing the dimensions of the new array.

Return Value

the new array.

Exceptions

  • NullPointerException - If the specified componentType is null.

  • IllegalArgumentException - if the specified dimensions argument is a zero-dimensional array, or if the number of requested dimensions exceeds the limit on the number of array dimensions supported by the implementation (typically 255), or if componentType is Void.TYPE.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative.

Example

The following example shows the usage of java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      String[][] stringArray = (String[][]) Array.newInstance(String.class, 3,3);

      Array.set(stringArray[0], 0, "Mahesh");
      Array.set(stringArray[1], 1, "Ramesh");
      Array.set(stringArray[2], 2, "Suresh");

      System.out.println("stringArray[0][0] = " + Array.get(stringArray[0], 0));
      System.out.println("stringArray[1][1] = " + Array.get(stringArray[1], 1));
      System.out.println("stringArray[2][2] = " + Array.get(stringArray[2], 2));
   }
}

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

stringArray[0][0] = Mahesh
stringArray[1][1] = Ramesh
stringArray[2][2] = Suresh

java.lang.reflect.Array.newInstance(Class<?> componentType, int length) Method Example

Description

The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method creates a new array with the specified component type and length.

Declaration

Following is the declaration for java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method.

public static Object newInstance(Class<?> componentType, int length)
   throws IllegalArgumentException, NegativeArraySizeException

Parameters

  • componentType - the Class object representing the component type of the new array.

  • length - an array of int representing the dimensions of the new array.

Return Value

the new array.

Exceptions

  • NullPointerException - If the specified componentType is null.

  • IllegalArgumentException - if the specified dimensions argument is a zero-dimensional array, or if the number of requested dimensions exceeds the limit on the number of array dimensions supported by the implementation (typically 255), or if componentType is Void.TYPE.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative.

Example

The following example shows the usage of java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      String[] stringArray = (String[]) Array.newInstance(String.class, 3);

      Array.set(stringArray, 0, "Mahesh");
      Array.set(stringArray, 1, "Ramesh");
      Array.set(stringArray, 2, "Suresh");

      System.out.println("stringArray[0] = " + Array.get(stringArray, 0));
      System.out.println("stringArray[1] = " + Array.get(stringArray, 1));
      System.out.println("stringArray[2] = " + Array.get(stringArray, 2));
   }
}

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

stringArray[0] = Mahesh
stringArray[1] = Ramesh
stringArray[2] = Suresh

java.lang.reflect.Array.set(Object array, int index, Object value) Method Example

Description

The java.lang.reflect.Array.set(Object array, int index, Object value) method sets the value of the indexed component of the specified array object to the specified new value. The new value is first automatically unwrapped if the array has a primitive component type.

Declaration

Following is the declaration for java.lang.reflect.Array.set(Object array, int index, Object value) method.

public static void set(Object array, int index, Object value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.set(Object array, int index, Object value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      String[] stringArray = (String[]) Array.newInstance(String.class, 3);

      Array.set(stringArray, 0, "Mahesh");
      Array.set(stringArray, 1, "Ramesh");
      Array.set(stringArray, 2, "Suresh");

      System.out.println("stringArray[0] = " + Array.get(stringArray, 0));
      System.out.println("stringArray[1] = " + Array.get(stringArray, 1));
      System.out.println("stringArray[2] = " + Array.get(stringArray, 2));
   }
}

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

stringArray[0] = Mahesh
stringArray[1] = Ramesh
stringArray[2] = Suresh

java.lang.reflect.Array.setBoolean(Object array, int index, boolean value) Method Example

Description

The java.lang.reflect.Array.setBoolean(Object array, int index, boolean value) method sets the value of the indexed component of the specified array object to the specified boolean value.

Declaration

Following is the declaration for java.lang.reflect.Array.set(Object array, int index, boolean value) method.

public static void setBoolean(Object array, int index, boolean value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setBoolean(Object array, int index, boolean value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      boolean[] array = new boolean[]{true,false, false};

      Array.setBoolean(array, 0, false);
      Array.setBoolean(array, 1, true);
      Array.setBoolean(array, 2, true);

      System.out.println("array[0] = " + Array.getBoolean(array, 0));
      System.out.println("array[1] = " + Array.getBoolean(array, 1));
      System.out.println("array[2] = " + Array.getBoolean(array, 2));
   }
}

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

array[0] = false
array[1] = true
array[2] = true

java.lang.reflect.Array.setByte(Object array, int index, byte value) Method Example

Description

The java.lang.reflect.Array.setByte(Object array, int index, byte value) method sets the value of the indexed component of the specified array object to the specified byte value.

Declaration

Following is the declaration for java.lang.reflect.Array.setByte(Object array, int index, byte value) method.

public static void setByte(Object array, int index, byte value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setByte(Object array, int index, byte value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      byte[] array = new byte[]{1,2, 3};

      Array.setByte(array, 0, (byte)2);
      Array.setByte(array, 1, (byte)3);
      Array.setByte(array, 2, (byte)4);

      System.out.println("array[0] = " + Array.getByte(array, 0));
      System.out.println("array[1] = " + Array.getByte(array, 1));
      System.out.println("array[2] = " + Array.getByte(array, 2));
   }
}

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

array[0] = 2
array[1] = 3
array[2] = 4

java.lang.reflect.Array.setChar(Object array, int index, char value) Method Example

Description

The java.lang.reflect.Array.setChar(Object array, int index, char value) method sets the value of the indexed component of the specified array object to the specified char value.

Declaration

Following is the declaration for java.lang.reflect.Array.setChar(Object array, int index, char value) method.

public static void setChar(Object array, int index, char value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setChar(Object array, int index, char value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      char[] array = new char[]{'1','2', '3'};

      Array.setChar(array, 0, '2');
      Array.setChar(array, 1, '3');
      Array.setChar(array, 2, '4');

      System.out.println("array[0] = " + Array.getChar(array, 0));
      System.out.println("array[1] = " + Array.getChar(array, 1));
      System.out.println("array[2] = " + Array.getChar(array, 2));
   }
}

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

array[0] = 2
array[1] = 3
array[2] = 4

java.lang.reflect.Array.setDouble(Object array, int index, double value) Method Example

Description

The java.lang.reflect.Array.setChar(Object array, int index, double value) method sets the value of the indexed component of the specified array object to the specified double value.

Declaration

Following is the declaration for java.lang.reflect.Array.setDouble(Object array, int index, double value) method.

public static void setDouble(Object array, int index, double value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setDouble(Object array, int index, double value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      double[] array = new double[]{1.0,2.0,3.0};

      Array.setDouble(array, 0, 2.0);
      Array.setDouble(array, 1, 3.0);
      Array.setDouble(array, 2, 4.0);

      System.out.println("array[0] = " + Array.getDouble(array, 0));
      System.out.println("array[1] = " + Array.getDouble(array, 1));
      System.out.println("array[2] = " + Array.getDouble(array, 2));
   }
}

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

array[0] = 2.0
array[1] = 3.0
array[2] = 4.0

java.lang.reflect.Array.setFloat(Object array, int index, float value) Method Example

Description

The java.lang.reflect.Array.setFloat(Object array, int index, float value) method sets the value of the indexed component of the specified array object to the specified float value.

Declaration

Following is the declaration for java.lang.reflect.Array.setFloat(Object array, int index, float value) method.

public static void setFloat(Object array, int index, float value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setFloat(Object array, int index, float value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      float[] array = new float[]{1.0f,2.0f,3.0f};

      Array.setFloat(array, 0, 2.0f);
      Array.setFloat(array, 1, 3.0f);
      Array.setFloat(array, 2, 4.0f);

      System.out.println("array[0] = " + Array.getFloat(array, 0));
      System.out.println("array[1] = " + Array.getFloat(array, 1));
      System.out.println("array[2] = " + Array.getFloat(array, 2));
   }
}

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

array[0] = 2.0
array[1] = 3.0
array[2] = 4.0

java.lang.reflect.Array.setInt(Object array, int index, int value) Method Example

Description

The java.lang.reflect.Array.setInt(Object array, int index, int value) method sets the value of the indexed component of the specified array object to the specified int value.

Declaration

Following is the declaration for java.lang.reflect.Array.setInt(Object array, int index, int value) method.

public static void setInt(Object array, int index, int value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setInt(Object array, int index, int value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      int[] array = new int[]{1,2,3};

      Array.setInt(array, 0, 2);
      Array.setInt(array, 1, 3);
      Array.setInt(array, 2, 4);

      System.out.println("array[0] = " + Array.getInt(array, 0));
      System.out.println("array[1] = " + Array.getInt(array, 1));
      System.out.println("array[2] = " + Array.getInt(array, 2));
   }
}

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

array[0] = 2
array[1] = 3
array[2] = 4

java.lang.reflect.Array.setLong(Object array, int index, long value) Method Example

Description

The java.lang.reflect.Array.setLong(Object array, int index, long value) method sets the value of the indexed component of the specified array object to the specified long value.

Declaration

Following is the declaration for java.lang.reflect.Array.setLong(Object array, int index, long value) method.

public static void setLong(Object array, int index, long value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setLong(Object array, int index, long value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      long[] array = new long[]{1,2,3};

      Array.setLong(array, 0, 2);
      Array.setLong(array, 1, 3);
      Array.setLong(array, 2, 4);

      System.out.println("array[0] = " + Array.getLong(array, 0));
      System.out.println("array[1] = " + Array.getLong(array, 1));
      System.out.println("array[2] = " + Array.getLong(array, 2));
   }
}

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

array[0] = 2
array[1] = 3
array[2] = 4

java.lang.reflect.Array.setShort(Object array, int index, short value) Method Example

Description

The java.lang.reflect.Array.setShort(Object array, int index, short value) method sets the value of the indexed component of the specified array object to the specified short value.

Declaration

Following is the declaration for java.lang.reflect.Array.setShort(Object array, int index, short value) method.

public static void setShort(Object array, int index, short value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array - the array.

  • index - the index.

  • value - the new value of the indexed component.

Exceptions

  • NullPointerException - If the specified object argument is null.

  • IllegalArgumentException - If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException - If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.setShort(Object array, int index, short value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {
      short[] array = new short[]{1,2,3};

      Array.setShort(array, 0, (short)2);
      Array.setShort(array, 1, (short)3);
      Array.setShort(array, 2, (short)4);

      System.out.println("array[0] = " + Array.getShort(array, 0));
      System.out.println("array[1] = " + Array.getShort(array, 1));
      System.out.println("array[2] = " + Array.getShort(array, 2));
   }
}

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

array[0] = 2
array[1] = 3
array[2] = 4

java.lang.reflect - Constructor

Introduction

The java.lang.reflect.Constructor class provides information about, and access to, a single constructor for a class. Constructor permits widening conversions to occur when matching the actual parameters to newInstance() with the underlying constructor's formal parameters, but throws an IllegalArgumentException if a narrowing conversion would occur.

Class declaration

Following is the declaration for java.lang.reflect.Constructor class −

public final class Constructor
   extends AccessibleObject
      implements GenericDeclaration, Member

Class methods

S.N. Method & Description
1 boolean equals(Object obj)

Compares this Constructor against the specified object.

2 <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.

3 Annotation[] getDeclaredAnnotations()

Returns all annotations that are directly present on this element.

4 Class<T> getDeclaringClass()

Returns the Class object representing the class that declares the constructor represented by this Constructor object.

5 Class<?>[] getExceptionTypes()

Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying constructor represented by this Constructor object.

6 Type[] getGenericExceptionTypes()

Returns an array of Type objects that represent the exceptions declared to be thrown by this Constructor object.

7 Type[] getGenericParameterTypes()

Returns an array of Type objects that represent the formal parameter types, in declaration order, of the method represented by this Constructor object.

8 int getModifiers()

Returns the Java language modifiers for the constructor represented by this Constructor object, as an integer.

9 String getName()

Returns the name of this constructor, as a string.

10 Annotation[][] getParameterAnnotations()

Returns an array of arrays that represent the annotations on the formal parameters, in declaration order, of the method represented by this Constructor object.

11 Class<?>[] getParameterTypes()

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object.

12 int hashCode()

Returns a hashcode for this Constructor.

13 boolean isSynthetic()

Returns true if this constructor is a synthetic constructor; returns false otherwise.

14 boolean isVarArgs()

Returns true if this constructor was declared to take a variable number of arguments; returns false otherwise.

15 T newInstance(Object... initargs)

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

16 String toGenericString()

Returns a string describing this Constructor, including type parameters.

17 String toString()

Returns a string describing this Constructor.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.reflect.AccessibleObject
  • java.lang.Object

java.lang.reflect.Constructor.equals(Object obj) 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.lang.reflect.Constructor.getAnnotation(Class<T> annotationClass) Method Example

Description

The java.lang.reflect.Constructor.getAnnotation(Class<T> annotationClass) method returns this element's annotation for the specified type if such an annotation is present, else null.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getAnnotation(Class<T> annotationClass) method.

public <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Parameters

  • annotationClass - the Class object corresponding to the annotation type.

Returns

this element's annotation for the specified annotation type if present on this element, else null.

Exceptions

  • NullPointerException - if the given annotation class is null.

Example

The following example shows the usage of java.lang.reflect.Constructor.getAnnotation(Class<T> annotationClass) method.

package com.tutorialspoint;

import java.lang.annotation.Annotation;
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();

      Annotation annotation = constructors[0].getAnnotation(CustomAnnotation.class);
      if(annotation instanceof CustomAnnotation){
         CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
         System.out.println("name: " + customAnnotation.name());
         System.out.println("value: " + customAnnotation.value());
      }
   }
}

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

name: sampleClassConstructor
value: Sample Constructor Annotation

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

Description

The java.lang.reflect.Constructor.getDeclaredAnnotations() method returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getDeclaredAnnotations() method.

public Annotation[] getDeclaredAnnotations()

Returns

All annotations directly present on this element.

Example

The following example shows the usage of java.lang.reflect.Constructor.getDeclaredAnnotations() method.

package com.tutorialspoint;

import java.lang.annotation.Annotation;
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();
      Annotation[] annotations = constructors[0].getDeclaredAnnotations();
      for(Annotation annotation : annotations){
         if(annotation instanceof CustomAnnotation){
            CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
            System.out.println("name: " + customAnnotation.name());
            System.out.println("value: " + customAnnotation.value());
         }
      }
   }
}

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

name: sampleClassConstructor
value: Sample Constructor Annotation

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

Description

The java.lang.reflect.Constructor.getDeclaringClass() method returns the Class object representing the class that declares the constructor represented by this Constructor object.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getDeclaringClass() method.

public Class<T> getDeclaringClass()

Returns

an object representing the declaring class of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Constructor.getDeclaringClass() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {

   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      Class declaringClass = constructors[0].getDeclaringClass();
      System.out.println(declaringClass.getName());
   }
}

class SampleClass {
   private String sampleField;

   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

com.tutorialspoint.SampleClass

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

Description

The java.lang.reflect.Constructor.getExceptionTypes() method returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying constructor represented by this Constructor object. Returns an array of length 0 if the constructor declares no exceptions in its throws clause.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getExceptionTypes() method.

public Class<?>[] getExceptionTypes()

Returns

the exception types declared as being thrown by the constructor this object represents.

Example

The following example shows the usage of java.lang.reflect.Constructor.getExceptionTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {

   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      Class[] exceptions = constructors[0].getExceptionTypes();
      for (int i = 0; i < exceptions.length; i++) {
         System.out.println(exceptions[i]);
      }
   }
}

class SampleClass {
   private String sampleField;

   public SampleClass() throws ArrayIndexOutOfBoundsException {
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

class java.lang.ArrayIndexOutOfBoundsException

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

Description

The java.lang.reflect.Constructor.getGenericExceptionTypes() method returns an array of Type objects that represent the exceptions declared to be thrown by this Constructor object. Returns an array of length 0 if the underlying method declares no exceptions in its throws clause.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getGenericExceptionTypes() method.

public Type[] getGenericExceptionTypes()

Returns

an array of Types that represent the exception types thrown by the underlying method.

Exceptions

  • GenericSignatureFormatError - if the generic method signature does not conform to the format specified in The Java Virtual Machine Specification.

  • TypeNotPresentException - if the underlying method's throws clause refers to a non-existent type declaration.

  • MalformedParameterizedTypeException - if the underlying method's throws clause refers to a parameterized type that cannot be instantiated for any reason.

Example

The following example shows the usage of java.lang.reflect.Constructor.getGenericExceptionTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;
import java.lang.reflect.Type;

public class ConstructorDemo {

   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      Type[] exceptions = constructors[0].getGenericExceptionTypes();
      for (int i = 0; i < exceptions.length; i++) {
         System.out.println(exceptions[i]);
      }
   }
}

class SampleClass {
   private String sampleField;

   public SampleClass() throws ArrayIndexOutOfBoundsException {
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

class java.lang.ArrayIndexOutOfBoundsException

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

Description

The java.lang.reflect.Constructor.getGenericParameterTypes() method returns an array of Type objects that represent the formal parameter types, in declaration order, of the method represented by this Constructor object. Returns an array of length 0 if the underlying method takes no parameters.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getGenericParameterTypes() method.

public Type[] getGenericParameterTypes()

Returns

an array of Types that represent the formal parameter types of the underlying method, in declaration order.

Exceptions

  • GenericSignatureFormatError - if the generic method signature does not conform to the format specified in The Java Virtual Machine Specification.

  • TypeNotPresentException - if any of the parameter types of the underlying method refers to a non-existent type declaration.

  • MalformedParameterizedTypeException - if any of the underlying method's parameter types refer to a parameterized type that cannot be instantiated for any reason.

Example

The following example shows the usage of java.lang.reflect.Constructor.getGenericParameterTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;
import java.lang.reflect.Type;

public class ConstructorDemo {

   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      Type[] parameters = constructors[1].getGenericParameterTypes();
      for (int i = 0; i < parameters.length; i++) {
         System.out.println(parameters[i]);
      }
   }
}

class SampleClass {
   private String sampleField;

   public SampleClass() throws ArrayIndexOutOfBoundsException {
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

class java.lang.String

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

Description

The java.lang.reflect.Constructor.getModifiers() method returns the Java language modifiers for the constructor represented by this Constructor object, as an integer. The Modifier class should be used to decode the modifiers.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getModifiers() method.

public int getModifiers()

Returns

the Java language modifiers for the underlying member.

Example

The following example shows the usage of java.lang.reflect.Constructor.getModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

public class ConstructorDemo {

   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getDeclaredConstructors();
      for (Constructor constructor : constructors) {
         System.out.println("Modifier: " + Modifier.toString(constructor.getModifiers()));
         System.out.println("Constructor: " + constructor.toGenericString());
      }
   }
}

class SampleClass {
   private String sampleField;

   public SampleClass() throws ArrayIndexOutOfBoundsException {
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

Modifier: public
Constructor: public com.tutorialspoint.SampleClass() throws java.lang.ArrayIndexOutOfBoundsException
Modifier: private
Constructor: private com.tutorialspoint.SampleClass(java.lang.String)

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

Description

The java.lang.reflect.Constructor.getName() method returns the name of this constructor, as a string. This is the binary name of the constructor's declaring class.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getName() method.

public String getName()

Returns

the simple name of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Constructor.getName() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {

   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getDeclaredConstructors();
      for (Constructor constructor : constructors) {
         System.out.println("Constructor: " + constructor.getName());
      }
   }
}

class SampleClass {
   private String sampleField;

   public SampleClass() throws ArrayIndexOutOfBoundsException {
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

Constructor: com.tutorialspoint.SampleClass
Constructor: com.tutorialspoint.SampleClass

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

Description

The java.lang.reflect.Constructor.getParameterAnnotations() method returns an array of arrays that represent the annotations on the formal parameters, in declaration order, of the method represented by this Constructor object. (Returns an array of length zero if the underlying method is parameterless. If the method has one or more parameters, a nested array of length zero is returned for each parameter with no annotations.) The annotation objects contained in the returned arrays are serializable. The caller of this method is free to modify the returned arrays; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getParameterAnnotations() method.

public Annotation[][] getParameterAnnotations()

Returns

the simple name of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Constructor.getParameterAnnotations() method.

package com.tutorialspoint;

import java.lang.annotation.Annotation;
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();
      Annotation[][] annotations = constructors[1].getParameterAnnotations();
      for(Annotation[] annotation1 : annotations){
         for(Annotation annotation : annotation1){
            if(annotation instanceof CustomAnnotation){
               CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
               System.out.println("name: " + customAnnotation.name());
               System.out.println("value: " + customAnnotation.value());
            }
         }
      }
   }
}

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

   
   public SampleClass(){
   }

   public SampleClass(@CustomAnnotation(name="sampleClassConstructor",  
      value = "Sample Constructor Annotation") 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 −

name: sampleClassConstructor
value: Sample Constructor Annotation

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

Description

The java.lang.reflect.Constructor.getParameterTypes() method returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object. Returns an array of length 0 if the underlying constructor takes no parameters.

Declaration

Following is the declaration for java.lang.reflect.Constructor.getParameterTypes() method.

public Class<?>[] getParameterTypes()

Returns

the parameter types for the constructor this object represents.

Example

The following example shows the usage of java.lang.reflect.Constructor.getParameterTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      Class[] parameterTypes = constructors[1].getParameterTypes();

      for(Class parameterType: parameterTypes){
         System.out.println(parameterType.getName());   
 
      }
   }
}

class SampleClass {
   private String sampleField;
   
   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

java.lang.String

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

Description

The java.lang.reflect.Constructor.hashCode() method returns a hashcode for this Constructor. The hashcode is the same as the hashcode for the underlying constructor's declaring class name.

Declaration

Following is the declaration for java.lang.reflect.Constructor.hashCode() method.

public int hashCode()

Returns

a hash code value for this object.

Example

The following example shows the usage of java.lang.reflect.Constructor.hashCode() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      System.out.println(constructors[1].hashCode());
   }
}

class SampleClass {
   private String sampleField;
   
   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

1743296200

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

Description

The java.lang.reflect.Constructor.isSynthetic() method returns true if this constructor is a synthetic constructor; returns false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Constructor.isSynthetic() method.

public boolean isSynthetic()

Returns

true if and only if this constructor is a synthetic constructor as defined by The Java Language Specification.

Example

The following example shows the usage of java.lang.reflect.Constructor.isSynthetic() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      System.out.println(constructors[1].isSynthetic());
   }
}

class SampleClass {
   private String sampleField;
   
   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

false

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

Description

The java.lang.reflect.Constructor.isVarArgs() method returns true if this constructor was declared to take a variable number of arguments; returns false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Constructor.isVarArgs() method.

public boolean isVarArgs()

Returns

true if an only if this constructor was declared to take a variable number of arguments.

Example

The following example shows the usage of java.lang.reflect.Constructor.isVarArgs() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      System.out.println(constructors[1].isVarArgs());
   }
}

class SampleClass {
   private String sampleField;
   
   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

false

java.lang.reflect.Constructor.newInstance(Object... initargs) Method Example

Description

The java.lang.reflect.Constructor.newInstance(Object... initargs) method uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

Declaration

Following is the declaration for java.lang.reflect.Constructor.newInstance(Object... initargs) method.

public T newInstance(Object... initargs) throws InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException

Parameters

  • initargs - array of objects to be passed as arguments to the constructor call; values of primitive types are wrapped in a wrapper object of the appropriate type (e.g. a float in a Float)

Returns

a new object created by calling the constructor this object represents.

Exceptions

  • IllegalAccessException - if this Constructor object is enforcing Java language access control and the underlying constructor is inaccessible.

  • IllegalArgumentException - if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion; if this constructor pertains to an enum type.

  • InstantiationException - if the class that declares the underlying constructor represents an abstract class.

  • InvocationTargetException - if the underlying constructor throws an exception.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Constructor.newInstance(Object... initargs) method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
         SecurityException, InstantiationException, IllegalAccessException, 
         IllegalArgumentException, InvocationTargetException {
      Constructor constructor = SampleClass.class.getConstructor(String.class);
      SampleClass sampleObject = (SampleClass)constructor.newInstance("data");
      System.out.println(sampleObject.getSampleField());
   }
}

class SampleClass {
   private String sampleField;
   
   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

data

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

Description

The java.lang.reflect.Constructor.toGenericString() method returns a string describing this Constructor, including type parameters. The string is formatted as the constructor access modifiers, if any, followed by an angle-bracketed comma separated list of the constructor's type parameters, if any, followed by the fully-qualified name of the declaring class, followed by a parenthesized, comma-separated list of the constructor's generic formal parameter types.

Declaration

Following is the declaration for java.lang.reflect.Constructor.toGenericString() method.

public String toGenericString()

Returns

a string describing this Constructor, include type parameters.

Example

The following example shows the usage of java.lang.reflect.Constructor.toGenericString() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      System.out.println(constructors[1].toGenericString());
   }
}

class SampleClass {
   private String sampleField;
   
   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

public com.tutorialspoint.SampleClass(java.lang.String)

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

Description

The java.lang.reflect.Constructor.toString() method returns a string describing this Constructor. The string is formatted as the constructor access modifiers, if any, followed by the fully-qualified name of the declaring class, followed by a parenthesized, comma-separated list of the constructor's formal parameter types.

Declaration

Following is the declaration for java.lang.reflect.Constructor.toString() method.

public String toString()

Returns

a string representation of the object.

Example

The following example shows the usage of java.lang.reflect.Constructor.toString() method.

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {
      Constructor[] constructors = SampleClass.class.getConstructors();
      System.out.println(constructors[1].toString());
   }
}

class SampleClass {
   private String sampleField;
   
   public SampleClass(){
   }

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

   public String getSampleField() {
      return sampleField;
   }

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

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

public com.tutorialspoint.SampleClass(java.lang.String)

java.lang.reflect - Field

Introduction

The java.lang.reflect.Field class provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field. A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

Class declaration

Following is the declaration for java.lang.reflect.Field class −

public final class Field
   extends AccessibleObject
      implements Member

Class methods

S.N. Method & Description
1 boolean equals(Object obj)

Compares this Field against the specified object.

2 Object get(Object obj)

Returns the value of the field represented by this Field, on the specified object.

3 <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.

4 boolean getBoolean(Object obj)

Gets the value of a static or instance boolean field.

5 byte getByte(Object obj)

Gets the value of a static or instance byte field.

6 char getChar(Object obj)

Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion.

7 Annotation[] getDeclaredAnnotations()

Returns all annotations that are directly present on this element.

8 Class<?> getDeclaringClass()

Returns the Class object representing the class or interface that declares the field represented by this Field object.

9 double getDouble(Object obj)

Gets the value of a static or instance field of type double or of another primitive type convertible to type double via a widening conversion.

10 float getFloat(Object obj)

Gets the value of a static or instance field of type float or of another primitive type convertible to type float via a widening conversion.

11 Type getGenericType()

Returns a Type object that represents the declared type for the field represented by this Field object.

12 int getInt(Object obj)

Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.

13 long getLong(Object obj)

Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion.

14 int getModifiers()

Returns the Java language modifiers for the field represented by this Field object, as an integer.

15 String getName()

RReturns the name of the field represented by this Field object.

16 short getShort(Object obj)

Gets the value of a static or instance field of type short or of another primitive type convertible to type short via a widening conversion.

17 Class<?> getType()

Returns a Class object that identifies the declared type for the field represented by this Field object.

18 int hashCode()

Returns a hashcode for this Field.

19 boolean isEnumConstant()

Returns true if this field represents an element of an enumerated type; returns false otherwise.

20 boolean isSynthetic()

Sets the field represented by this Field object on the specified object argument to the specified new value.

21 void setBoolean(Object obj, boolean z)

Sets the value of a field as a boolean on the specified object.

22 void setByte(Object obj, byte b)

Sets the value of a field as a byte on the specified object.

23 void setChar(Object obj, char c)

Sets the value of a field as a char on the specified object.

24 void setDouble(Object obj, double d)

Sets the value of a field as a double on the specified object.

25 void setFloat(Object obj, float f)

Sets the value of a field as a float on the specified object.

26 void setInt(Object obj, int i)

Sets the value of a field as an int on the specified object.

27 void setLong(Object obj, long l)

Sets the value of a field as a long on the specified object.

28 void setShort(Object obj, short s)

Sets the value of a field as a short on the specified object.

29 String toGenericString()

Returns a string describing this Field, including its generic type.

30 String toString()

Returns a string describing this Field.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.reflect.AccessibleObject
  • java.lang.Object

java.lang.reflect.Field.equals(Object obj) 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.lang.reflect.Field.get(Object obj) Method Example

Description

The java.lang.reflect.Field.get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.

Declaration

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

public Object get(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.get(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) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
      sampleObject.setSampleField("data");
      
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.get(sampleObject));
   }
}

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

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   public String 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 −

Fields are not equal.

java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) Method Example

Description

The java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) method returns this element's annotation for the specified type if such an annotation is present, else null.

Declaration

Following is the declaration for java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) method.

public <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Parameters

  • annotationClass - the Class object corresponding to the annotation type.

Returns

this element's annotation for the specified annotation type if present on this element, else null.

Exceptions

  • NullPointerException - if the given annotation class is null.

Example

The following example shows the usage of java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) method.

package com.tutorialspoint;

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

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
      Field field = SampleClass.class.getField("sampleField");
      Annotation annotation = field.getAnnotation(CustomAnnotation.class);
      if(annotation instanceof CustomAnnotation){
         CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
         System.out.println("name: " + customAnnotation.name());
         System.out.println("value: " + customAnnotation.value());
      }
   }
}

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

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   public String 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 −

name: sampleClassField
value: Sample Field Annotation

java.lang.reflect.Field.getBoolean(Object obj) Method Example

Description

The java.lang.reflect.Field.getBoolean(Object obj) method gets the value of a static or instance boolean field.

Declaration

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

public boolean getBoolean(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getBoolean(sampleObject));
   }
}

class SampleClass {
   public static boolean sampleField = true;  
}

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

true

java.lang.reflect.Field.getByte(Object obj) Method Example

Description

The java.lang.reflect.Field.getByte(Object obj) method gets the value of a static or instance byte field.

Declaration

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

public byte getByte(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getByte(sampleObject));
   }
}

class SampleClass {
   public static byte sampleField = 7;  
}

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

7

java.lang.reflect.Field.getChar(Object obj) Method Example

Description

The java.lang.reflect.Field.getChar(Object obj) method gets the value of a static or instance char field.

Declaration

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

public char getChar(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getChar(sampleObject));
   }
}

class SampleClass {
   public static char sampleField = 'a';  
}

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

a

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

Description

The java.lang.reflect.Field.getDeclaredAnnotations() method returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.Field.getDeclaredAnnotations() method.

public Annotation[] getDeclaredAnnotations()

Returns

All annotations directly present on this element.

Example

The following example shows the usage of java.lang.reflect.Field.getDeclaredAnnotations() method.

package com.tutorialspoint;

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

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
      Field field = SampleClass.class.getField("sampleField");
      Annotation[] annotations = field.getDeclaredAnnotations();
      for(Annotation annotation : annotations){
         if(annotation instanceof CustomAnnotation){
            CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
            System.out.println("name: " + customAnnotation.name());
            System.out.println("value: " + customAnnotation.value());
         }
      }
   }
}

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

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   public String 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 −

name: sampleClassField
value: Sample Field Annotation

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

Description

The java.lang.reflect.Field.getDeclaringClass() method returns the Class object representing the class or interface that declares the field represented by this Field object.

Declaration

Following is the declaration for java.lang.reflect.Field.getDeclaringClass() method.

public Class<T> getDeclaringClass()

Returns

an object representing the declaring class of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Field.getDeclaringClass() method.

package com.tutorialspoint;

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

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
      Field field = SampleClass.class.getField("sampleField");
      Class declaringClass = field.getDeclaringClass();
      System.out.println(declaringClass.getName());
   }
}

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

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   public String 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 −

com.tutorialspoint.SampleClass

java.lang.reflect.Field.getDouble(Object obj) Method Example

Description

The java.lang.reflect.Field.getDouble(Object obj) method gets the value of a static or instance double field.

Declaration

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

public double getDouble(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getDouble(sampleObject));
   }
}

class SampleClass {
   public static double sampleField = 5.0d;
}

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

5.0

java.lang.reflect.Field.getFloat(Object obj) Method Example

Description

The java.lang.reflect.Field.getFloat(Object obj) method gets the value of a static or instance float field.

Declaration

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

public float getFloat(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getFloat(sampleObject));
   }
}

class SampleClass {
   public static float sampleField = 5.0f;
}

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

5.0

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

Description

The java.lang.reflect.Field.getGenericType() method returns a Type object that represents the declared type for the field represented by this Field object.

Declaration

Following is the declaration for java.lang.reflect.Field.getGenericType() method.

public Type getGenericType()

Returns

a Type object that represents the declared type for the field represented by this Field object.

Exceptions

  • GenericSignatureFormatError - if the generic field signature does not conform to the format specified in The Java Virtual Machine Specification.

  • TypeNotPresentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • MalformedParameterizedTypeException - if the generic signature of the underlying field refers to a parameterized type that cannot be instantiated for any reason.

Example

The following example shows the usage of java.lang.reflect.Field.getGenericType() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getGenericType());
   }
}

class SampleClass {
   public static float sampleField = 5.0f;
}

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

float

java.lang.reflect.Field.getInt(Object obj) Method Example

Description

The java.lang.reflect.Field.getInt(Object obj) method gets the value of a static or instance int field.

Declaration

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

public int getInt(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getInt(sampleObject));
   }
}

class SampleClass {
   public static int sampleField = 5;
}

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

5

java.lang.reflect.Field.getLong(Object obj) Method Example

Description

The java.lang.reflect.Field.getLong(Object obj) method gets the value of a static or instance long field.

Declaration

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

public long getLong(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getLong(sampleObject));
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

5

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

Description

The java.lang.reflect.Field.getModifiers() method returns the Java language modifiers for the field represented by this Field object, as an integer. The Modifier class should be used to decode the modifiers.

Declaration

Following is the declaration for java.lang.reflect.Field.getModifiers() method.

public int getModifiers()

Returns

the Java language modifiers for the underlying member.

Example

The following example shows the usage of java.lang.reflect.Field.getModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println("Modifier: " + Modifier.toString(field.getModifiers()));
   }
}

class SampleClass {
   public static long sampleField = 5;
}


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

public static

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

Description

The java.lang.reflect.Field.getName() method returns the name of the field represented by this Field object.

Declaration

Following is the declaration for java.lang.reflect.Field.getName() method.

public String getName()

Returns

the simple name of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Field.getName() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getName());
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

sampleField

java.lang.reflect.Field.getShort(Object obj) Method Example

Description

The java.lang.reflect.Field.getShort(Object obj) method gets the value of a static or instance short field.

Declaration

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

public short getShort(Object obj)
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - object from which the represented field's value is to be extracted.

Returns

the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getShort(sampleObject));
   }
}

class SampleClass {
   public static short sampleField = 5;
}

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

5

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

Description

The java.lang.reflect.Field.getType() method returns a Class object that identifies the declared type for the field represented by this Field object.

Declaration

Following is the declaration for java.lang.reflect.Field.getType() method.

public Class<?> getType()

Returns

a Class object identifying the declared type of the field represented by this object.

Example

The following example shows the usage of java.lang.reflect.Field.getType() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.getType());
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

sampleField

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

Description

The java.lang.reflect.Field.hashCode() method returns a hashcode for this Field. This is computed as the exclusive-or of the hashcodes for the underlying field's declaring class name and its name.

Declaration

Following is the declaration for java.lang.reflect.Field.hashCode() method.

public int hashCode()

Returns

a hash code value for this object.

Example

The following example shows the usage of java.lang.reflect.Field.hashCode() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.hashCode());
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

1616225208

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

Description

The java.lang.reflect.Field.isEnumConstant() method returns true if this field represents an element of an enumerated type; returns false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Field.isEnumConstant() method.

public boolean isEnumConstant()

Returns

true if and only if this field represents an element of an enumerated type.

Example

The following example shows the usage of java.lang.reflect.Field.isEnumConstant() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.isEnumConstant());
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

false

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

Description

The java.lang.reflect.Field.isSynthetic() method returns true if this field Returns true if this field is a synthetic field; returns false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Field.isSynthetic() method.

public boolean isSynthetic()

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Example

The following example shows the usage of java.lang.reflect.Field.isSynthetic() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.isSynthetic());
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

false

java.lang.reflect.Field.set(Object obj, Object value) Method Example

Description

The java.lang.reflect.Field.set(Object obj, Object value) method sets the field represented by this Field object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type.

Declaration

Following is the declaration for java.lang.reflect.Field.set(Object obj, Object value) method.

public void set(Object obj, Object value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.set(sampleObject, 7);
      
      System.out.println(field.getInt(sampleObject));
   }
}

class SampleClass {
   public static int sampleField = 5;
}

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

7

java.lang.reflect.Field.setBoolean(Object obj, boolean value) Method Example

Description

The java.lang.reflect.Field.setBoolean(Object obj, Object value) method sets the value of a field as a boolean on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setBoolean(Object obj, boolean value) method.

public void setBoolean(Object obj, boolean value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

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

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setBoolean(sampleObject, false);
      
      System.out.println(field.getBoolean(sampleObject));
   }
}

class SampleClass {
   public static boolean sampleField = true;
}

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

false

java.lang.reflect.Field.setByte(Object obj, byte value) Method Example

Description

The java.lang.reflect.Field.setByte(Object obj, byte value) method sets the value of a field as a byte on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setBoolean(Object obj, byte value) method.

public void setByte(Object obj, byte value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.setByte(Object obj, byte value) method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setByte(sampleObject, (byte)7);
      
      System.out.println(field.getByte(sampleObject));
   }
}

class SampleClass {
   public static byte sampleField = 3;
}

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

7

java.lang.reflect.Field.setChar(Object obj, char value) Method Example

Description

The java.lang.reflect.Field.setChar(Object obj, char value) method sets the value of a field as a char on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setChar(Object obj, char value) method.

public void setChar(Object obj, char value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.setChar(Object obj, char value) method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setChar(sampleObject, 'B');
      
      System.out.println(field.getChar(sampleObject));
   }
}

class SampleClass {
   public static char sampleField = 'A';
}

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

B

java.lang.reflect.Field.setDouble(Object obj, double value) Method Example

Description

The java.lang.reflect.Field.setDouble(Object obj, double value) method sets the value of a field as a double on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setDouble(Object obj, double value) method.

public void setDouble(Object obj, double value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.setDouble(Object obj, double value) method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setDouble(sampleObject, 7.0);
      
      System.out.println(field.getDouble(sampleObject));
   }
}

class SampleClass {
   public static double sampleField = 5.0;
}

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

7.0

java.lang.reflect.Field.setFloat(Object obj, double value) Method Example

Description

The java.lang.reflect.Field.setFloat(Object obj, double value) method sets the value of a field as a double on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setFloat(Object obj, double value) method.

public void setFloat(Object obj, double value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.setFloat(Object obj, double value) method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setFloat(sampleObject, 7.0f);
      
      System.out.println(field.getFloat(sampleObject));
   }
}

class SampleClass {
   public static float sampleField = 5.0f;
}

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

7.0

java.lang.reflect.Field.setInt(Object obj, int value) Method Example

Description

The java.lang.reflect.Field.setInt(Object obj, int value) method sets the value of a field as a int on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setInt(Object obj, int value) method.

public void setInt(Object obj, int value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.setInt(Object obj, int value) method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setInt(sampleObject, 7);
      
      System.out.println(field.getInt(sampleObject));
   }
}

class SampleClass {
   public static int sampleField = 5;
}

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

7

java.lang.reflect.Field.setLong(Object obj, long value) Method Example

Description

The java.lang.reflect.Field.setLong(Object obj, long value) method sets the value of a field as a long on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setLong(Object obj, long value) method.

public void setLong(Object obj, long value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.setLong(Object obj, long value) method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setLong(sampleObject, 7);
      
      System.out.println(field.getLong(sampleObject));
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

7

java.lang.reflect.Field.setShort(Object obj, short value) Method Example

Description

The java.lang.reflect.Field.setShort(Object obj, short value) method sets the value of a field as a short on the specified object.

Declaration

Following is the declaration for java.lang.reflect.Field.setShort(Object obj, short value) method.

public void setShort(Object obj, short value) 
   throws IllegalArgumentException, IllegalAccessException

Parameters

  • obj - the object whose field should be modified.

  • value - the new value for the field of obj being modified.

Returns

true if and only if this field is a synthetic field as defined by the Java Language Specification.

Exceptions

  • IllegalAccessException - if this Field object is enforcing Java language access control and the underlying field is inaccessible.

  • IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).

  • NullPointerException - if the specified object is null and the field is an instance field.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Field.setShort(Object obj, short value) method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
            
      Field field = SampleClass.class.getField("sampleField");
      
      field.setShort(sampleObject, (short)7);
      
      System.out.println(field.getShort(sampleObject));
   }
}

class SampleClass {
   public static short sampleField = 5;
}

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

7

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

Description

The java.lang.reflect.Field.toGenericString() method returns a string describing this Field, including its generic type. The format is the access modifiers for the field, if any, followed by the generic field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field.

Declaration

Following is the declaration for java.lang.reflect.Field.toGenericString() method.

public String toGenericString()

Returns

a string describing this Field, including its generic type.

Example

The following example shows the usage of java.lang.reflect.Field.toGenericString() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.toGenericString());
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

public static long com.tutorialspoint.SampleClass.sampleField

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

Description

The java.lang.reflect.Field.toString() method returns a string describing this Field. The format is the access modifiers for the field, if any, followed by the field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field.

Declaration

Following is the declaration for java.lang.reflect.Field.toString() method.

public String toString()

Returns

a string describing this Field, including its generic type.

Example

The following example shows the usage of java.lang.reflect.Field.toString() method.

package com.tutorialspoint;

import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.toString());
   }
}

class SampleClass {
   public static long sampleField = 5;
}

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

public static long com.tutorialspoint.SampleClass.sampleField

java.lang.reflect - Method

Introduction

The java.lang.reflect.Method class provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.

Class declaration

Following is the declaration for java.lang.reflect.Method class −

public final class Method<T>
   extends AccessibleObject
      implements GenericDeclaration, Member

Class methods

S.N. Method & Description
1 boolean equals(Object obj)

Compares this Method against the specified object.

2 <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.

3 Annotation[] getDeclaredAnnotations()

Returns all annotations that are directly present on this element.

4 Class<T> getDeclaringClass()

Returns the Class object representing the class that declares the method represented by this Method object.

5 Object getDefaultValue()

Returns the default value for the annotation member represented by this Method instance.

6 Class<?>[] getExceptionTypes()

Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying constructor represented by this Constructor object.

7 Type[] getGenericExceptionTypes()

Returns an array of Type objects that represent the exceptions declared to be thrown by this Constructor object.

8 Type[] getGenericParameterTypes()

Returns an array of Type objects that represent the formal parameter types, in declaration order, of the method represented by this Constructor object.

9 Type getGenericReturnType()

Returns a Type object that represents the formal return type of the method represented by this Method object.

10 int getModifiers()

Returns the Java language modifiers for the method represented by this Method object, as an integer.

11 String getName()

Returns the name of this method, as a string.

12 Annotation[][] getParameterAnnotations()

Returns an array of arrays that represent the annotations on the formal parameters, in declaration order, of the method represented by this Method object.

13 Class<?>[] getParameterTypes()

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Method object.

14 Class<?> getReturnType()

Returns a Class object that represents the formal return type of the method represented by this Method object.

15 int hashCode()

Returns a hashcode for this Constructor.

16 Object invoke(Object obj, Object... args)

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

17 boolean isBridge()

Returns true if this method is a bridge method; returns false otherwise.

18 boolean isSynthetic()

Returns true if this method is a synthetic method; returns false otherwise.

19 boolean isVarArgs()

Returns true if this method was declared to take a variable number of arguments; returns false otherwise.

20 String toGenericString()

Returns a string describing this Method, including type parameters.

21 String toString()

Returns a string describing this Method.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.reflect.AccessibleObject
  • java.lang.Object

java.lang.reflect.Method.equals(Object obj) Method Example

Description

The java.lang.reflect.Method.equals(Object obj) method compares this Method against the specified object. Returns true if the objects are the same. Two Method 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.Method.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.Method.equals(Object obj) method.

package com.tutorialspoint;

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

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      boolean isEquals = methods[0].equals(methods[1]);
      System.out.println("Methods are " + (isEquals?"equal.":"not equal."));
   }
}

class SampleClass {
   private String sampleField;
   private String sampleField1;

   public SampleClass(){
   }

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

   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;
   } 
}

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

Methods are not equal.

java.lang.reflect.Method.getAnnotation(Class<T> annotationClass) Method Example

Description

The java.lang.reflect.Method.getAnnotation(Class<T> annotationClass) method returns this element's annotation for the specified type if such an annotation is present, else null.

Declaration

Following is the declaration for java.lang.reflect.Method.getAnnotation(Class<T> annotationClass) method.

public <T extends Annotation> T getAnnotation(Class<T> annotationClass)

Parameters

  • annotationClass - the Class object corresponding to the annotation type.

Returns

this element's annotation for the specified annotation type if present on this element, else null.

Exceptions

  • NullPointerException - if the given annotation class is null.

Example

The following example shows the usage of java.lang.reflect.Method.getAnnotation(Class<T> annotationClass) method.

package com.tutorialspoint;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();

      Annotation annotation = methods[0].getAnnotation(CustomAnnotation.class);
      if(annotation instanceof CustomAnnotation){
         CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
         System.out.println("name: " + customAnnotation.name());
         System.out.println("value: " + customAnnotation.value());
      }
   }
}

@CustomAnnotation(name="SampleClass",  value = "Sample Class Annotation")
class SampleClass {
   private String sampleField;
   
   @CustomAnnotation(name="getSampleMethod",  value = "Sample Method Annotation")
   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 −

name: getSampleMethod
value: Sample Method Annotation

java.lang.reflect.Method.getDeclaredAnnotations() Method Example

Description

The java.lang.reflect.Method.getDeclaredAnnotations() method returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.Method.getDeclaredAnnotations() method.

public Annotation[] getDeclaredAnnotations()

Returns

All annotations directly present on this element.

Example

The following example shows the usage of java.lang.reflect.Method.getDeclaredAnnotations() method.

package com.tutorialspoint;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Annotation[] annotations = methods[0].getDeclaredAnnotations();
      for(Annotation annotation : annotations){
         if(annotation instanceof CustomAnnotation){
            CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
            System.out.println("name: " + customAnnotation.name());
            System.out.println("value: " + customAnnotation.value());
         }
      }
   }
}

@CustomAnnotation(name="SampleClass",  value = "Sample Class Annotation")
class SampleClass {
   private String sampleField;
   
   @CustomAnnotation(name="getSampleMethod",  value = "Sample Method Annotation")
   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 −

name: getSampleMethod
value: Sample Method Annotation

java.lang.reflect.Method.getDeclaringClass() Method Example

Description

The java.lang.reflect.Method.getDeclaringClass() method returns the Class object representing the class that declares the method represented by this Method object.

Declaration

Following is the declaration for java.lang.reflect.Method.getDeclaringClass() method.

public Class<T> getDeclaringClass()

Returns

an object representing the declaring class of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Method.getDeclaringClass() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Class declaringClass = methods[0].getDeclaringClass();
      System.out.println(declaringClass.getName());
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

com.tutorialspoint.SampleClass

java.lang.reflect.Method.getDefaultValue() Method Example

Description

The java.lang.reflect.Method.getDefaultValue() method returns the default value for the annotation member represented by this Method instance. If the member is of a primitive type, an instance of the corresponding wrapper type is returned. Returns null if no default is associated with the member, or if the method instance does not represent a declared member of an annotation type.

Declaration

Following is the declaration for java.lang.reflect.Method.getDefaultValue() method.

public Object getDefaultValue()

Returns

the default value for the annotation member represented by this Method instance.

Exceptions

  • TypeNotPresentException - if the annotation is of type Class and no definition can be found for the default class value.

Example

The following example shows the usage of java.lang.reflect.Method.getDefaultValue() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(methods[0].getDefaultValue());
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

null

java.lang.reflect.Method.getExceptionTypes() Method Example

Description

The java.lang.reflect.Method.getExceptionTypes() method returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying method represented by this Method object. Returns an array of length 0 if the method declares no exceptions in its throws clause.

Declaration

Following is the declaration for java.lang.reflect.Method.getExceptionTypes() method.

public Class<?>[] getExceptionTypes()

Returns

the exception types declared as being thrown by the method this object represents.

Example

The following example shows the usage of java.lang.reflect.Method.getExceptionTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Class[] exceptions = methods[0].getExceptionTypes();
      for (int i = 0; i < exceptions.length; i++) {
         System.out.println(exceptions[i]);
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() throws ArrayIndexOutOfBoundsException{
      return sampleField;
   }

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

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

class java.lang.ArrayIndexOutOfBoundsException

java.lang.reflect.Method.getGenericExceptionTypes() Method Example

Description

The java.lang.reflect.Method.getGenericExceptionTypes() method returns an array of Type objects that represent the exceptions declared to be thrown by this Method object. Returns an array of length 0 if the underlying method declares no exceptions in its throws clause.

Declaration

Following is the declaration for java.lang.reflect.Method.getGenericExceptionTypes() method.

public Type[] getGenericExceptionTypes()

Returns

an array of Types that represent the exception types thrown by the underlying method.

Exceptions

  • GenericSignatureFormatError - if the generic method signature does not conform to the format specified in The Java Virtual Machine Specification.

  • TypeNotPresentException - if the underlying method's throws clause refers to a non-existent type declaration.

  • MalformedParameterizedTypeException - if the underlying method's throws clause refers to a parameterized type that cannot be instantiated for any reason.

Example

The following example shows the usage of java.lang.reflect.Method.getGenericExceptionTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Type[] exceptions = methods[0].getGenericExceptionTypes();
      for (int i = 0; i < exceptions.length; i++) {
         System.out.println(exceptions[i]);
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() throws ArrayIndexOutOfBoundsException {
      return sampleField;
   }

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

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

class java.lang.ArrayIndexOutOfBoundsException

java.lang.reflect.Method.getGenericParameterTypes() Method Example

Description

The java.lang.reflect.Method.getGenericParameterTypes() method returns an array of Type objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns an array of length 0 if the underlying method takes no parameters.

Declaration

Following is the declaration for java.lang.reflect.Method.getGenericParameterTypes() method.

public Type[] getGenericParameterTypes()

Returns

an array of Types that represent the formal parameter types of the underlying method, in declaration order.

Exceptions

  • GenericSignatureFormatError - if the generic method signature does not conform to the format specified in The Java Virtual Machine Specification.

  • TypeNotPresentException - if any of the parameter types of the underlying method refers to a non-existent type declaration.

  • MalformedParameterizedTypeException - if any of the underlying method's parameter types refer to a parameterized type that cannot be instantiated for any reason.

Example

The following example shows the usage of java.lang.reflect.Method.getGenericParameterTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Type[] parameters = methods[1].getGenericParameterTypes();
      for (int i = 0; i < parameters.length; i++) {
         System.out.println(parameters[i]);
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

class java.lang.String

java.lang.reflect.Method.getGenericReturnType() Method Example

Description

The java.lang.reflect.Method.getGenericReturnType() method returns a Type object that represents the formal return type of the method represented by this Method object.

Declaration

Following is the declaration for java.lang.reflect.Method.getGenericReturnType() method.

public Type getGenericReturnType()

Returns

a Type object that represents the formal return type of the underlying method.

Exceptions

  • GenericSignatureFormatError - if the generic method signature does not conform to the format specified in The Java Virtual Machine Specification.

  • TypeNotPresentException - if any of the parameter types of the underlying method refers to a non-existent type declaration.

  • MalformedParameterizedTypeException - if any of the underlying method's parameter types refer to a parameterized type that cannot be instantiated for any reason.

Example

The following example shows the usage of java.lang.reflect.Method.getGenericReturnType() method.

package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Type returnType = methods[0].getGenericReturnType();
      System.out.println(returnType);
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

class java.lang.String

java.lang.reflect.Method.getModifiers() Method Example

Description

The java.lang.reflect.Method.getModifiers() method returns the Java language modifiers for the method represented by this Method object, as an integer. The Modifier class should be used to decode the modifiers.

Declaration

Following is the declaration for java.lang.reflect.Method.getModifiers() method.

public int getModifiers()

Returns

the Java language modifiers for the underlying member.

Example

The following example shows the usage of java.lang.reflect.Method.getModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      for (Method method : methods) {
         System.out.println("Modifier: " + Modifier.toString(method.getModifiers()));
         System.out.println("Method: " + method.toGenericString());
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() throws ArrayIndexOutOfBoundsException {
      return sampleField;
   }

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

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

Modifier: public
Method: public java.lang.String com.tutorialspoint.SampleClass.getSampleField() throws java.lang.ArrayIndexOutOfBoundsException
Modifier: public
Method: public void com.tutorialspoint.SampleClass.setSampleField(java.lang.String)
Modifier: public final
Method: public final void java.lang.Object.wait() throws java.lang.InterruptedException
Modifier: public final
Method: public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
Modifier: public final native
Method: public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
Modifier: public
Method: public boolean java.lang.Object.equals(java.lang.Object)
Modifier: public
Method: public java.lang.String java.lang.Object.toString()
Modifier: public native
Method: public native int java.lang.Object.hashCode()
Modifier: public final native
Method: public final native java.lang.Class<?> java.lang.Object.getClass()
Modifier: public final native
Method: public final native void java.lang.Object.notify()
Modifier: public final native
Method: public final native void java.lang.Object.notifyAll()

java.lang.reflect.Method.getName() Method Example

Description

The java.lang.reflect.Method.getName() method returns the name of this method, as a string. This is the binary name of the method's declaring class.

Declaration

Following is the declaration for java.lang.reflect.Method.getName() method.

public String getName()

Returns

the simple name of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Method.getName() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {

   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      for (Method method : methods) {
         System.out.println("Method: " + method.getName());
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

Method: getSampleField
Method: setSampleField
Method: wait
Method: wait
Method: wait
Method: equals
Method: toString
Method: hashCode
Method: getClass
Method: notify
Method: notifyAll

java.lang.reflect.Method.getParameterAnnotations() Method Example

Description

The java.lang.reflect.Method.getParameterAnnotations() method returns an array of arrays that represent the annotations on the formal parameters, in declaration order, of the method represented by this Method object. (Returns an array of length zero if the underlying method is parameterless. If the method has one or more parameters, a nested array of length zero is returned for each parameter with no annotations.) The annotation objects contained in the returned arrays are serializable. The caller of this method is free to modify the returned arrays; it will have no effect on the arrays returned to other callers.

Declaration

Following is the declaration for java.lang.reflect.Method.getParameterAnnotations() method.

public Annotation[][] getParameterAnnotations()

Returns

the simple name of the underlying member.

Example

The following example shows the usage of java.lang.reflect.Method.getParameterAnnotations() method.

package com.tutorialspoint;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Annotation[][] annotations = methods[1].getParameterAnnotations();
      for(Annotation[] annotation1 : annotations){
         for(Annotation annotation : annotation1){
            if(annotation instanceof CustomAnnotation){
               CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
               System.out.println("name: " + customAnnotation.name());
               System.out.println("value: " + customAnnotation.value());
            }
         }
      }
   }
}

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

   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(@CustomAnnotation(name="sampleClassMethod",  
      value = "Sample Method Annotation") 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 −

name: sampleClassMethod
value: Sample Method Annotation

java.lang.reflect.Method.getParameterTypes() Method Example

Description

The java.lang.reflect.Method.getParameterTypes() method returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns an array of length 0 if the underlying method takes no parameters.

Declaration

Following is the declaration for java.lang.reflect.Method.getParameterTypes() method.

public Class<?>[] getParameterTypes()

Returns

the parameter types for the method this object represents.

Example

The following example shows the usage of java.lang.reflect.Method.getParameterTypes() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Class[] parameterTypes = methods[1].getParameterTypes();

      for(Class parameterType: parameterTypes){
         System.out.println(parameterType.getName());   
 
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

java.lang.String

java.lang.reflect.Method.getReturnType() Method Example

Description

The java.lang.reflect.Method.getReturnType() method returns a Class object that represents the formal return type of the method represented by this Method object.

Declaration

Following is the declaration for java.lang.reflect.Method.getReturnType() method.

public Class<?> getReturnType()

Returns

the return type for the method this object represents.

Example

The following example shows the usage of java.lang.reflect.Method.getReturnType() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      Class returnType = methods[0].getReturnType();

      System.out.println(returnType.getName());
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

java.lang.String

java.lang.reflect.Method.hashCode() Method Example

Description

The java.lang.reflect.Method.hashCode() method returns a hashcode for this Method. The hashcode is the same as the hashcode for the underlying method's declaring class name.

Declaration

Following is the declaration for java.lang.reflect.Method.hashCode() method.

public int hashCode()

Returns

a hash code value for this object.

Example

The following example shows the usage of java.lang.reflect.Method.hashCode() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(methods[1].hashCode());
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

269515110

java.lang.reflect.Method.invoke(Object obj, Object... args) Method Example

Description

The java.lang.reflect.Method.invoke(Object obj, Object... args) method invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

Declaration

Following is the declaration for java.lang.reflect.Method.invoke(Object obj, Object... args) method.

public Object invoke(Object obj, Object... args)
   throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException

Parameters

  • obj - the object the underlying method is invoked from.

  • args - the arguments used for the method call.

Returns

the result of dispatching the method represented by this object on obj with parameters args.

Exceptions

  • IllegalAccessException - if this Method object is enforcing Java language access control and the underlying method is inaccessible.

  • IllegalArgumentException - if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.

  • InvocationTargetException - if the underlying method throws an exception.

  • NullPointerException - if the specified object is null and the method is an instance method.

  • ExceptionInInitializerError - if the initialization provoked by this method fails.

Example

The following example shows the usage of java.lang.reflect.Method.invoke(Object obj, Object... args) method.

package com.tutorialspoint;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) 
      throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
      Method[] methods = SampleClass.class.getMethods();
      SampleClass sampleObject = new SampleClass();
      methods[1].invoke(sampleObject, "data");
      System.out.println(methods[0].invoke(sampleObject));
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() {
      return sampleField;
   }

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

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

data

java.lang.reflect.Method.isBridge() Method Example

Description

The java.lang.reflect.Method.isBridge() method returns true if this method is a bridge method; returns false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Method.isBridge() method.

public boolean isBridge()

Returns

true if and only if this method is a bridge method as defined by The Java Language Specification.

Example

The following example shows the usage of java.lang.reflect.Method.isBridge() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(methods[1].isBridge());
   }
}

class SampleClass {
   private String sampleField;
   
   public String getSampleField() {
      return sampleField;
   }

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

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

false

java.lang.reflect.Method.isSynthetic() Method Example

Description

The java.lang.reflect.Method.isSynthetic() method returns true if this method is a synthetic method; returns false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Method.isSynthetic() method.

public boolean isSynthetic()

Returns

true if and only if this method is a synthetic method as defined by The Java Language Specification.

Example

The following example shows the usage of java.lang.reflect.Method.isSynthetic() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(methods[1].isSynthetic());
   }
}

class SampleClass {
   private String sampleField;
   
   public String getSampleField() {
      return sampleField;
   }

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

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

false

java.lang.reflect.Method.isVarArgs() Method Example

Description

The java.lang.reflect.Method.isVarArgs() method returns true if this method was declared to take a variable number of arguments; returns false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Method.isVarArgs() method.

public boolean isVarArgs()

Returns

true if an only if this method was declared to take a variable number of arguments.

Example

The following example shows the usage of java.lang.reflect.Method.isVarArgs() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(methods[1].isVarArgs());
   }
}

class SampleClass {
   private String sampleField;
   
   public String getSampleField() {
      return sampleField;
   }

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

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

false

java.lang.reflect.Method.toGenericString() Method Example

Description

The java.lang.reflect.Method.toGenericString() method returns a string describing this Method, including type parameters. The string is formatted as the method access modifiers, if any, followed by an angle-bracketed comma-separated list of the method's type parameters, if any, followed by the method's generic return type, followed by a space, followed by the class declaring the method, followed by a period, followed by the method name, followed by a parenthesized, comma-separated list of the method's generic formal parameter types.

Declaration

Following is the declaration for java.lang.reflect.Method.toGenericString() method.

public String toGenericString()

Returns

a string describing this Method, include type parameters.

Example

The following example shows the usage of java.lang.reflect.Method.toGenericString() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(methods[1].toGenericString());
   }
}

class SampleClass {
   private String sampleField;
   
   public String getSampleField() {
      return sampleField;
   }

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

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

public void com.tutorialspoint.SampleClass.setSampleField(java.lang.String)

java.lang.reflect.Method.toString() Method Example

Description

The java.lang.reflect.Method.toString() method returns a string describing this Method. The string is formatted as the method access modifiers, if any, followed by the method return type, followed by a space, followed by the class declaring the method, followed by a period, followed by the method name, followed by a parenthesized, comma-separated list of the method's formal parameter types.

Declaration

Following is the declaration for java.lang.reflect.Method.toString() method.

public String toString()

Returns

a string representation of the object.

Example

The following example shows the usage of java.lang.reflect.Method.toString() method.

package com.tutorialspoint;

import java.lang.reflect.Method;

public class MethodDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(methods[1].toString());
   }
}

class SampleClass {
   private String sampleField;
   
   public String getSampleField() {
      return sampleField;
   }

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

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

public void com.tutorialspoint.SampleClass.setSampleField(java.lang.String)

java.lang.reflect - Modifier

Introduction

The java.lang.reflect.Modifier class provides static methods and constants to decode class and member access modifiers. The sets of modifiers are represented as integers with distinct bit positions representing different modifiers. The values for the constants representing the modifiers are taken from the tables in sections 4.1, 4.4, 4.5, and 4.7 of The Java Virtual Machine Specification.

Class declaration

Following is the declaration for java.lang.reflect.Modifier class −

public class Modifier
   extends Object

Fields

Following are the fields for java.lang.reflect.Modifier class −

  • static int ABSTRACT - The int value representing the abstract modifier.

  • static int FINAL - The int value representing the final modifier.

  • static int INTERFACE - The int value representing the interface modifier.

  • static int NATIVE - The int value representing the native modifier.

  • static int PRIVATE - The int value representing the private modifier.

  • static int PROTECTED - The int value representing the protected modifier.

  • static int PUBLIC - The int value representing the public modifier.

  • static int STATIC - The int value representing the static modifier.

  • static int STRICT - The int value representing the strictfp modifier.

  • static int SYNCHRONIZED - The int value representing the synchronized modifier.

  • static int TRANSIENT - The int value representing the transient modifier.

  • static int VOLATILE - The int value representing the volatile modifier.

Constructors

S.N. Constructor & Description
1 Modifier()

Default Constructor.

Class methods

S.N. Method & Description
1 static int classModifiers()

Return an int value OR-ing together the source language modifiers that can be applied to a class.

2 static int constructorModifiers()

Return an int value OR-ing together the source language modifiers that can be applied to a constructor.

3 static int fieldModifiers()

Return an int value OR-ing together the source language modifiers that can be applied to a field.

4 static int interfaceModifiers()

Return an int value OR-ing together the source language modifiers that can be applied to an interface.

5 static boolean isAbstract(int mod)

Return true if the integer argument includes the abstract modifier, false otherwise.

6 static boolean isFinal(int mod)

Return true if the integer argument includes the final modifier, false otherwise.

7 static boolean isInterface(int mod)

Return true if the integer argument includes the interface modifier, false otherwise.

8 static boolean isNative(int mod)

Return true if the integer argument includes the native modifier, false otherwise.

9 static boolean isPrivate(int mod)

Return true if the integer argument includes the private modifier, false otherwise.

10 static boolean isProtected(int mod)

Return true if the integer argument includes the protected modifier, false otherwise.

11 static boolean isPublic(int mod)

Return true if the integer argument includes the public modifier, false otherwise.

12 static boolean isStatic(int mod)

Return true if the integer argument includes the static modifier, false otherwise.

13 static boolean isStrict(int mod)

Return true if the integer argument includes the strictfp modifier, false otherwise.

14 static boolean isSynchronized(int mod)

Return true if the integer argument includes the synchronized modifier, false otherwise.

15 static boolean isTransient(int mod)

Return true if the integer argument includes the transient modifier, false otherwise.

16 static boolean isVolatile(int mod)

Return true if the integer argument includes the volatile modifier, false otherwise.

17 static int methodModifiers()

Return an int value OR-ing together the source language modifiers that can be applied to a method.

18 static String toString(int mod)

Return a string describing the access modifier flags in the specified modifier.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.lang.reflect.Modifier.classModifiers() Method Example

Description

The java.lang.reflect.Modifier.classModifiers() method return an int value OR-ing together the source language modifiers that can be applied to a class.

Declaration

Following is the declaration for java.lang.reflect.Modifier.classModifiers() method.

public static int classModifiers()

Returns

an int value OR-ing together the source language modifiers that can be applied to a class.

Example

The following example shows the usage of java.lang.reflect.Modifier.classModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      System.out.println(Modifier.toString(Modifier.classModifiers()));
   }
}

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

public protected private abstract static final strictfp

java.lang.reflect.Modifier.constructorModifiers() Method Example

Description

The java.lang.reflect.Modifier.constructorModifiers() method return an int value OR-ing together the source language modifiers that can be applied to a constructor.

Declaration

Following is the declaration for java.lang.reflect.Modifier.constructorModifiers() method.

public static int constructorModifiers()

Returns

an int value OR-ing together the source language modifiers that can be applied to a constructor.

Example

The following example shows the usage of java.lang.reflect.Modifier.constructorModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      System.out.println(Modifier.toString(Modifier.constructorModifiers()));
   }
}

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

public protected private

java.lang.reflect.Modifier.fieldModifiers() Method Example

Description

The java.lang.reflect.Modifier.fieldModifiers() method return an int value OR-ing together the source language modifiers that can be applied to a field.

Declaration

Following is the declaration for java.lang.reflect.Modifier.fieldModifiers() method.

public static int fieldModifiers()

Returns

an int value OR-ing together the source language modifiers that can be applied to a field.

Example

The following example shows the usage of java.lang.reflect.Modifier.fieldModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      System.out.println(Modifier.toString(Modifier.fieldModifiers()));
   }
}

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

public protected private static final transient volatile

java.lang.reflect.Modifier.interfaceModifiers() Method Example

Description

The java.lang.reflect.Modifier.interfaceModifiers() method return an int value OR-ing together the source language modifiers that can be applied to a interface.

Declaration

Following is the declaration for java.lang.reflect.Modifier.interfaceModifiers() method.

public static int interfaceModifiers()

Returns

an int value OR-ing together the source language modifiers that can be applied to a interface.

Example

The following example shows the usage of java.lang.reflect.Modifier.interfaceModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      System.out.println(Modifier.toString(Modifier.interfaceModifiers()));
   }
}

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

public protected private abstract static strictfp

java.lang.reflect.Modifier.isAbstract(int mod) Method Example

Description

The java.lang.reflect.Modifier.isAbstract(int mod) method return true if the integer argument includes the abstract modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isAbstract(int mod) method.

public static boolean isAbstract(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the abstract modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isAbstract(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(Modifier.isAbstract(methods[0].getModifiers()));
   }
}

abstract class SampleClass {
   private String sampleField;
   
   public abstract String getSampleField();
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isFinal(int mod) Method Example

Description

The java.lang.reflect.Modifier.isFinal(int mod) method return true if the integer argument includes the final modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isFinal(int mod) method.

public static boolean isFinal(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the final modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isFinal(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      Method[] methods = SampleClass.class.getMethods();
      System.out.println(Modifier.isFinal(methods[0].getModifiers()));
   }
}

class SampleClass {
   private String sampleField;
   
   public final String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isInterface(int mod) Method Example

Description

The java.lang.reflect.Modifier.isInterface(int mod) method return true if the integer argument includes the interface modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isInterface(int mod) method.

public static boolean isInterface(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the interface modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isInterface(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      System.out.println(Modifier.isInterface(SampleClass.class.getModifiers()));
   }
}

interface SampleClass {
   String getSampleField();
}

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

true

java.lang.reflect.Modifier.isNative(int mod) Method Example

Description

The java.lang.reflect.Modifier.isNative(int mod) method return true if the integer argument includes the native modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isNative(int mod) method.

public static boolean isNative(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the native modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isNative(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isNative(field.getModifiers()));
   }
}

class SampleClass {
   private String sampleField;
   
   public final String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

false

java.lang.reflect.Modifier.isPrivate(int mod) Method Example

Description

The java.lang.reflect.Modifier.isPrivate(int mod) method return true if the integer argument includes the private modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isPrivate(int mod) method.

public static boolean isPrivate(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the private modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isPrivate(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isPrivate(field.getModifiers()));
   }
}

class SampleClass {
   private String sampleField;
   
   public final String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isProtected(int mod) Method Example

Description

The java.lang.reflect.Modifier.isProtected(int mod) method return true if the integer argument includes the protected modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isProtected(int mod) method.

public static boolean isProtected(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the protected modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isProtected(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isProtected(field.getModifiers()));
   }
}

class SampleClass {
   protected String sampleField;
   
   public final String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isPublic(int mod) Method Example

Description

The java.lang.reflect.Modifier.isPublic(int mod) method return true if the integer argument includes the public modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isPublic(int mod) method.

public static boolean isPublic(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the public modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isPublic(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isPublic(field.getModifiers()));
   }
}

class SampleClass {
   public String sampleField;
   
   public final String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isStatic(int mod) Method Example

Description

The java.lang.reflect.Modifier.isStatic(int mod) method return true if the integer argument includes the static modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isStatic(int mod) method.

public static boolean isStatic(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the static modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isStatic(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isStatic(field.getModifiers()));
   }
}

class SampleClass {
   public static String sampleField;
   
   public final String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isStrict(int mod) Method Example

Description

The java.lang.reflect.Modifier.isStrict(int mod) method return true if the integer argument includes the strictfp modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isStrict(int mod) method.

public static boolean isStrict(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the strictfp modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isStrict(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isStrict(field.getModifiers()));
   }
}

class SampleClass {
   public static String sampleField;
   
   public final String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

false

java.lang.reflect.Modifier.isSynchronized(int mod) Method Example

Description

The java.lang.reflect.Modifier.isSynchronized(int mod) method return true if the integer argument includes the synchronized modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isSynchronized(int mod) method.

public static boolean isSynchronized(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the synchronized modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isSynchronized(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Method [] methods = SampleClass.class.getMethods();
      System.out.println(Modifier.isSynchronized((methods[0].getModifiers())));
   }
}

class SampleClass {
   public static String sampleField;
   
   public final synchronized String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isTransient(int mod) Method Example

Description

The java.lang.reflect.Modifier.isTransient(int mod) method return true if the integer argument includes the transient modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isTransient(int mod) method.

public static boolean isTransient(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the transient modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isTransient(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isTransient((field.getModifiers())));
   }
}

class SampleClass {
   public transient String sampleField;
   
   public final synchronized String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.isVolatile(int mod) Method Example

Description

The java.lang.reflect.Modifier.isVolatile(int mod) method return true if the integer argument includes the volatile modifier, false otherwise.

Declaration

Following is the declaration for java.lang.reflect.Modifier.isVolatile(int mod) method.

public static boolean isVolatile(int mod)

Parameters

  • mod - a set of modifiers.

Returns

true if mod includes the volatile modifier; false otherwise.

Example

The following example shows the usage of java.lang.reflect.Modifier.isVolatile(int mod) method.

package com.tutorialspoint;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) throws NoSuchFieldException, SecurityException {
      Field field = SampleClass.class.getDeclaredField("sampleField");
      System.out.println(Modifier.isVolatile((field.getModifiers())));
   }
}

class SampleClass {
   public volatile String sampleField;
   
   public final synchronized String getSampleField(){
      return sampleField;   
   }
   
   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

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

true

java.lang.reflect.Modifier.methodModifiers() Method Example

Description

The java.lang.reflect.Modifier.methodModifiers() method return an int value OR-ing together the source language modifiers that can be applied to a method.

Declaration

Following is the declaration for java.lang.reflect.Modifier.methodModifiers() method.

public static int methodModifiers()

Returns

an int value OR-ing together the source language modifiers that can be applied to a method.

Example

The following example shows the usage of java.lang.reflect.Modifier.methodModifiers() method.

package com.tutorialspoint;

import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      System.out.println(Modifier.toString(Modifier.methodModifiers()));
   }
}

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

public protected private abstract static final synchronized native strictfp

java.lang.reflect.Modifier.toString() Method Example

Description

The java.lang.reflect.Modifier.toString() method returns a string describing the access modifier flags in the specified modifier.

Declaration

Following is the declaration for java.lang.reflect.Modifier.toString() method.

public static String toString(int mod)

Returns

a string representation of the set of modifiers represented by mod.

Example

The following example shows the usage of java.lang.reflect.Modifier.toString() method.

package com.tutorialspoint;

import java.lang.reflect.Modifier;

public class ModifierDemo {
   public static void main(String[] args) {
      System.out.println(Modifier.toString(Modifier.toString()));
   }
}

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

public protected private abstract static final synchronized native strictfp

java.lang.reflect - Proxy

Introduction

The java.lang.reflect.Proxy class provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.

Class declaration

Following is the declaration for java.lang.reflect.Proxy class −

public class Proxy
   extends Object
      implements Serializable

Fields

Following are the fields for java.lang.reflect.Proxy class −

  • protected InvocationHandler h - the invocation handler for this proxy instance.

Constructors

S.N. Constructor & Description
1 protected Proxy(InvocationHandler h)

Constructs a new Proxy instance from a subclass (typically, a dynamic proxy class) with the specified value for its invocation handler.

Class methods

S.N. Method & Description
1 static InvocationHandler getInvocationHandler(Object proxy)

Returns the invocation handler for the specified proxy instance.

2 static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)

Returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces.

3 static boolean isProxyClass(Class<?> cl)

Returns true if and only if the specified class was dynamically generated to be a proxy class using the getProxyClass method or the newProxyInstance method.

4 static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.lang.reflect.Proxy.getInvocationHandler(Object proxy) Method Example

Description

The java.lang.reflect.Proxy.getInvocationHandler(Object proxy) method returns the invocation handler for the specified proxy instance.

Declaration

Following is the declaration for java.lang.reflect.Proxy.getInvocationHandler(Object proxy) method.

public static InvocationHandler getInvocationHandler(Object proxy)
   throws IllegalArgumentException

Parameters

  • proxy - the proxy instance to return the invocation handler for.

Returns

the invocation handler for the proxy instance.

Exceptions

  • IllegalArgumentException - if the argument is not a proxy instance.

Example

The following example shows the usage of java.lang.reflect.Proxy.getInvocationHandler(Object proxy) method.

package com.tutorialspoint;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {
   public static void main(String[] args) throws IllegalArgumentException {
      InvocationHandler handler = new SampleInvocationHandler() ;
      SampleInterface proxy = (SampleInterface) Proxy.newProxyInstance(
         SampleInterface.class.getClassLoader(),
         new Class[] { SampleInterface.class },
         handler);
      Class invocationHandler = Proxy.getInvocationHandler(proxy).getClass();

      System.out.println(invocationHandler.getName());
   }
}

class SampleInvocationHandler implements InvocationHandler {

   @Override
   public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
      System.out.println("Welcome to TutorialsPoint");   
      return null;
   }
}

interface SampleInterface {
   void showMessage();
}

class SampleClass implements SampleInterface {
   public void showMessage(){
      System.out.println("Hello World");   
   }
}

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

com.tutorialspoint.SampleInvocationHandler

java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) Method Example

Description

The java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) method returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. The proxy class will be defined by the specified class loader and will implement all of the supplied interfaces. If a proxy class for the same permutation of interfaces has already been defined by the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically and defined by the class loader.

Declaration

Following is the declaration for java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) method.

public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
throws IllegalArgumentException

Parameters

  • loader - the class loader to define the proxy class.

  • interfaces - the list of interfaces for the proxy class to implement.

Returns

a proxy class that is defined in the specified class loader and that implements the specified interfaces.

Exceptions

  • IllegalArgumentException - if any of the restrictions on the parameters that may be passed to getProxyClass are violated.

  • NullPointerException - if the interfaces array argument or any of its elements are null.

Example

The following example shows the usage of java.lang.reflect.Proxy.getProxyClass(ClassLoader loader, Class<?>... interfaces) method.

package com.tutorialspoint;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {
   public static void main(String[] args) throws 
      IllegalArgumentException, InstantiationException, 
         IllegalAccessException, InvocationTargetException, 
            NoSuchMethodException, SecurityException {
      InvocationHandler handler = new SampleInvocationHandler() ;

      Class proxyClass = Proxy.getProxyClass(
      SampleClass.class.getClassLoader(), new Class[] { SampleInterface.class });
      SampleInterface proxy = (SampleInterface) proxyClass.
         getConstructor(new Class[] { InvocationHandler.class }).
         newInstance(new Object[] { handler });
      proxy.showMessage();
   }
}

class SampleInvocationHandler implements InvocationHandler {

   @Override
   public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
      System.out.println("Welcome to TutorialsPoint");   
      return null;
   }
}

interface SampleInterface {
   void showMessage();
}

class SampleClass implements SampleInterface {
   public void showMessage(){
      System.out.println("Hello World");   
   }
}

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

com.tutorialspoint.SampleInvocationHandler

java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) Method Example

Description

The java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) method returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.

Declaration

Following is the declaration for java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) method.

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
   InvocationHandler h)
      throws IllegalArgumentException

Parameters

  • loader - the class loader to define the proxy class.

  • interfaces - the list of interfaces for the proxy class to implement.

  • h - the invocation handler to dispatch method invocations to.

Returns

A proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and that implements the specified interfaces.

Exceptions

  • IllegalArgumentException - if any of the restrictions on the parameters that may be passed to getProxyClass are violated.

  • NullPointerException - if the interfaces array argument or any of its elements are null, or if the invocation handler, h, is null.

Example

The following example shows the usage of java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) method.

package com.tutorialspoint;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {
   public static void main(String[] args) throws IllegalArgumentException {
      InvocationHandler handler = new SampleInvocationHandler() ;
      SampleInterface proxy = (SampleInterface) Proxy.newProxyInstance(
         SampleInterface.class.getClassLoader(),
         new Class[] { SampleInterface.class },
         handler);
      Class invocationHandler = Proxy.getInvocationHandler(proxy).getClass();

      System.out.println(invocationHandler.getName());
   }
}

class SampleInvocationHandler implements InvocationHandler {

   @Override
   public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
      System.out.println("Welcome to TutorialsPoint");   
      return null;
   }
}

interface SampleInterface {
   void showMessage();
}

class SampleClass implements SampleInterface {
   public void showMessage(){
      System.out.println("Hello World");   
   }
}

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

com.tutorialspoint.SampleInvocationHandler

java.lang.reflect.Proxy.isProxyClass(Class<?> cl) Method Example

Description

The java.lang.reflect.Proxy.isProxyClass(Class<?> cl) method returns true if and only if the specified class was dynamically generated to be a proxy class using the getProxyClass method or the newProxyInstance method.

Declaration

Following is the declaration for java.lang.reflect.Proxy.isProxyClass(Class<?> cl) method.

public static boolean isProxyClass(Class<?> cl)

Parameters

  • cl - the class to test.

Returns

true if the class is a proxy class and false otherwise.

Exceptions

  • NullPointerException - if cl is null.

Example

The following example shows the usage of java.lang.reflect.Proxy.isProxyClass(Class<?> cl) method.

package com.tutorialspoint;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {
   public static void main(String[] args) 
      throws IllegalArgumentException, InstantiationException, 
         IllegalAccessException, InvocationTargetException, 
         NoSuchMethodException, SecurityException {
      InvocationHandler handler = new SampleInvocationHandler() ;

      Class proxyClass = Proxy.getProxyClass(
      SampleClass.class.getClassLoader(), new Class[] { SampleInterface.class });
      SampleInterface proxy = (SampleInterface) proxyClass.
         getConstructor(new Class[] { InvocationHandler.class }).
         newInstance(new Object[] { handler });
      System.out.println(Proxy.isProxyClass(proxyClass));
      proxy.showMessage();
   }
}

class SampleInvocationHandler implements InvocationHandler {

   @Override
   public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
      System.out.println("Welcome to TutorialsPoint");   
      return null;
   }
}

interface SampleInterface {
   void showMessage();
}

class SampleClass implements SampleInterface {
   public void showMessage(){
      System.out.println("Hello World");   
   }
}

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

true
Welcome to TutorialsPoint

java.lang.reflect - Interfaces

Introduction

The java.lang.reflect Interfaces contains the interfaces which are used to obtain reflective information about classes and objects.

Interface Summary

S.N. Interface & Description
1

AnnotatedElement

Represents an annotated element of the program currently running in this VM.

2

GenericArrayType

GenericArrayType represents an array type whose component type is either a parameterized type or a type variable.

3

GenericDeclaration

A common interface for all entities that declare type variables.

4

InvocationHandler

InvocationHandler is the interface implemented by the invocation handler of a proxy instance.

5

Member

Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.

6

ParameterizedType

ParameterizedType represents a parameterized type such as Collection<String>.

7

Type

Type is the common superinterface for all types in the Java programming language.

8

List<E>

This is an ordered collection (also known as a sequence).

9

TypeVariable<D extends GenericDeclaration>

TypeVariable is the common superinterface for type variables of kinds.

10

WildcardType

WildcardType represents a wildcard type expression, such as ?, ? extends Number, or ? super Integer.

java.lang.reflect - Exceptions

Introduction

The java.lang.reflect Exceptions contains the exceptions which can occur during reflection operations.

Interface Summary

S.N. Exception & Description
1

InvocationTargetException

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.

2

MalformedParameterizedTypeException

Thrown when a semantically malformed parameterized type is encountered by a reflective method that needs to instantiate it.

3

UndeclaredThrowableException

Thrown by a method invocation on a proxy instance if its invocation handler's invoke method throws a checked exception (a Throwable that is not assignable to RuntimeException or Error) that is not assignable to any of the exception types declared in the throws clause of the method that was invoked on the proxy instance and dispatched to the invocation handler.

java.lang.reflect - Error

Introduction

The java.lang.reflect Error contains the error which can occur during reflection operations.

Interface Summary

S.N. Error & Description
1

GenericSignatureFormatError

Thrown when a syntactically malformed signature attribute is encountered by a reflective method that needs to interpret the generic signature information for a type, method or constructor.



Advertisements