Home | | Object Oriented Programming | | The Complete Reference Java | | Internet Programming | | Web Programming | Reflection - java.lang.reflect package

Chapter: Java The Complete Reference - The Java Library - Regular Expressions and Other Packages

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Reflection - java.lang.reflect package

Reflection is the ability of software to analyze itself. This is provided by the java.lang.reflect package and elements in Class.

Reflection

 

Reflection is the ability of software to analyze itself. This is provided by the java.lang.reflect package and elements in Class. Reflection is an important capability, especially when using components called Java Beans. It allows you to analyze a software component and describe its capabilities dynamically, at run time rather than at compile time. For example, by using reflection, you can determine what methods, constructors, and fields a class supports.

 

Reflection was introduced in Chapter 12. It is examined further here.

 

The package java.lang.reflect includes several interfaces. Of special interest is Member, which defines methods that allow you to get information about a field, constructor, or method of a class. There are also ten classes in this package. These are listed in Table 30-2.

Class : Primary Function

AccessibleObject : Allows you to bypass the default access control checks.

Array : Allows you to dynamically create and manipulate arrays.

Constructor : Provides information about a constructor.

Executable : An abstract superclass extended by Method and Constructor. (Added by JDK 8.)

Field : Provides information about a field.

Method : Provides information about a method.

Modifier : Provides information about class and member access modifiers.

Parameter : Provides information about parameters. (Added by JDK 8.)

Proxy : Supports dynamic proxy classes.

ReflectPermission : Allows reflection of private or protected members of a class.

Table 30-2   Classes Defined in java.lang.reflect

 

The following application illustrates a simple use of the Java reflection capabilities. It prints the constructors, fields, and methods of the class java.awt.Dimension. The program begins by using the forName( ) method of Class to get a class object for java.awt.Dimension. Once this is obtained, getConstructors( ), getFields( ), and getMethods( ) are used to analyze this class object. They return arrays of Constructor, Field, and Method objects that provide the information about the object. The Constructor, Field, and Method classes define several methods that can be used to obtain information about an object. You will want to explore these on your own. However, each supports the toString( ) method. Therefore, using Constructor, Field, and Method objects as arguments to the println( ) method is straightforward, as shown in the program.

 

// Demonstrate reflection.

import java.lang.reflect.*; public class ReflectionDemo1 {

 

public static void main(String args[]) { try {

 

Class<?> c = Class.forName("java.awt.Dimension"); System.out.println("Constructors:");

 

Constructor<?> constructors[] = c.getConstructors(); for(int i = 0; i < constructors.length; i++) {

System.out.println(" " + constructors[i]);

 

}

 

System.out.println("Fields:"); Field fields[] = c.getFields();

 

for(int i = 0; i < fields.length; i++) { System.out.println(" " + fields[i]);

 

}

 

System.out.println("Methods:");

Method methods[] = c.getMethods();

 

for(int i = 0; i < methods.length; i++) { System.out.println(" " + methods[i]);

 

}

 

}

 

catch(Exception e) { System.out.println("Exception: " + e);

}

 

}

 

}

 

Here is the output from this program. (The precise order may differ slightly from that shown.)

 

Constructors:

Public java.awt.Dimension(int,int)

Public java.awt.Dimension()

Public java.awt.Dimension(java.awt.Dimension)

Fields:

Public int java.awt.Dimension.width

Public int java.awt.Dimension.height

Methods:

Public int java.awt.Dimension.hashCode()

Public boolean java.awt.Dimension.equals(java.lang.Object)

Public java.lang.String java.awt.Dimension.toString()

publicjava.awt.Dimension java.awt.Dimension.getSize()

publicvoid java.awt.Dimension.setSize(double,double)

publicvoid java.awt.Dimension.setSize(java.awt.Dimension)

publicvoid java.awt.Dimension.setSize(int,int)

publicdouble java.awt.Dimension.getHeight()

publicdouble java.awt.Dimension.getWidth()

publicjava.lang.Object java.awt.geom.Dimension2D.clone()

publicvoid java.awt.geom.

Dimension2D.setSize(java.awt.geom.Dimension2D)

publicfinal native java.lang.Class java.lang.Object.getClass()

publicfinal native void java.lang.Object.wait(long)

throws java.lang.InterruptedException

publicfinal void java.lang.Object.wait()

throws java.lang.InterruptedException

publicfinal void java.lang.Object.wait(long,int)

throws java.lang.InterruptedException

publicfinal native void java.lang.Object.notify()

publicfinal native void java.lang.Object.notifyAll()

The next example uses Java’s reflection capabilities to obtain the public methods of a class. The program begins by instantiating class A. The getClass( ) method is applied to this object reference, and it returns the Class object for class A. The getDeclaredMethods( ) method returns an array of Method objects that describe only the methods declared by this class. Methods inherited from superclasses such as Object are not included.

 

Each element of the methods array is then processed. The getModifiers( ) method returns an int containing flags that describe which modifiers apply for this element. The Modifier class provides a set of isX methods, shown in Table 30-3, that can be used to examine this value. For example, the static method isPublic( ) returns true if its argument

Method :- Description

 

static boolean isAbstract(int val)  :-   Returns true if val has the abstract flag set and false otherwise.

 

static boolean isFinal(int val):- Returns true if val has the final flag set and false otherwise.

 

static boolean isInterface(int val):- Returns true if val has the interface flag set and false otherwise.

 

static boolean isNative(int val):- Returns true if val has the native flag set and false otherwise.

 

static boolean isPrivate(int val):- Returns true if val has the private flag set and false otherwise.

 

static boolean isProtected(int val):- Returns true if val has the protected flag set and false otherwise.

 

static boolean isPublic(int val):- Returns true if val has the public flag set and false otherwise.

 

static boolean isStatic(int val):- Returns true if val has the static flag set and false otherwise.

 

static boolean isStrict(int val):- Returns true if val has the strict flag set and false otherwise.

 

static boolean isSynchronized(int val):- Returns true if val has the synchronized flag set and false otherwise.

 static boolean isTransient(int val):- Returns true if val has the transient flag set and false otherwise.

 

static boolean isVolatile(int val):- Returns true if val has the volatile flag set and false otherwise.

 

Table 30-3   The “is” Methods Defined by Modifier That Determine Modifiers

 

includes the public modifier. Otherwise, it returns false. In the following program, if the method supports public access, its name is obtained by the getName( ) method and is then printed.

 

 

// Show public methods.

import java.lang.reflect.*; public class ReflectionDemo2 {

public static void main(String args[]) {

 

try {

 

A a = new A();

 

Class<?> c = a.getClass(); System.out.println("Public Methods:"); Method methods[] = c.getDeclaredMethods(); for(int i = 0; i < methods.length; i++) {

 

int modifiers = methods[i].getModifiers(); if(Modifier.isPublic(modifiers)) {

 

System.out.println(" " + methods[i].getName());

 

}

 

}

 

}

 

catch(Exception e) { System.out.println("Exception: " + e);

}

 

}

 

}

 

class A {

 

public void a1() {

 

}

 

public void a2() {

 

}

 

protected void a3() {

 

}

 

private void a4() {

 

}

 

}

 

Here is the output from this program:

 

Public Methods: a1

 

a2

 

Modifier also includes a set of static methods that return the type of modifiers that can be applied to a specific type of program element. These methods are

 

static int classModifiers( )

 

static int constructorModifiers( ) static int fieldModifiers( )

 

static int interfaceModifiers( ) static int methodModifiers( )

 

static int parameterModifiers( ) (Added by JDK 8.)

 

For example, methodModifiers( ) returns the modifiers that can be applied to a method. Each method returns flags, packed into an int, that indicate which modifiers are legal. The modifier values are defined by constants in Modifier, which include PROTECTED, PUBLIC, PRIVATE, STATIC, FINAL, and so on.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.