java reflection concept and working

Post on 04-Jul-2015

1.550 Views

Category:

Education

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Java Reflection Concept and Working

TRANSCRIPT

Advanced Java ProgrammingLecture-02: Reflection

Aatif Kamal, Dept. of ComputingAatif.kamal@seecs.edu.pk

Study Source: http://download.oracle.com/javase/tutorial/reflect/

Reflection Overview

Reflection API

The “Class" class

Class methods

Array class

Member interface

Method class

invoking a method,

throwing exceptions

Field class

accessible objects

Background

Programs are just another kind of data

Source code is text

Manipulate it line by line, or by parsing expressions

Compiled programs are data, too

Integers and strings are bytes in memory that you

interpret a certain way

Instructions in methods are just bytes too

No reason why a program can't inspect itself

How objects work

class Point {

public Point(int x, int y) {

}

public getX() { }

public getY() { }

protected int x, y;

}

5

3

{…}

{…}

{…}

Point(int,int)

getX()

getY()

x

y

object

class

Every object is either a reference or primitive type.

5

Defining Reflection

Introduced in Java 1.1. Called the "Java Core Reflection API"

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine

Allows you to find out information about any object, including its methods and fields, at run time.

Can no longer get away with this called an enabling technology because it supports Java language elements such as:

Java Beans, Serialization, and Remote Method Invocation (RMI).

JBoss, Tomcat, Eclipse, etc. are reflection-based

6

Reflection Can be Used To . . .

construct new class instances and new arrays

access and modify fields of objects and classes

invoke methods on objects and classes

access and modify elements of arrays

Uses of Reflection

Extensibility Features

An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.

Class Browsers and Visual Development Environments

A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.

Debuggers and Test Tools

Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

Drawbacks of Reflection

Reflection is powerful, but should not be used

indiscriminately.

If it is possible to perform an operation without using reflection, then

it is preferable to avoid using it.

Performance Overhead

Because reflection involves types that are dynamically resolved,

certain Java virtual machine optimizations can not be performed.

Slower performance than their non-reflective counterparts,

should be avoided in sections of code which are called frequently

in performance-sensitive applications.

Security Restrictions

Reflection requires a runtime permission which may not be

present when running under a security manager.

Code which has to run in a restricted security context, such as

in an Applet.

Drawbacks of Reflection

Exposure of Internals

Since reflection allows code to perform operations that would be

illegal in non-reflective code,

Accessing private fields and methods, the use of reflection

can result in unexpected side-effects,

Reflective code breaks abstractions and therefore may

change behavior with upgrades of the platform.

Class c = Class.forName(“java.lang.String”);Object o = c.newInstance();

Reflection - Classes

Reflection is a dynamic language feature

Used to query object and class information static Class Class.forName(String className)

Obtain a java.lang.Class object

i.e. Class.forName(“java.lang.String”) gets an object corresponding to class String

Object Class.newInstance()

Object constructor in disguise

Create a new object of a given class

This makes a new empty string.

Running Example Most typical use of reflection: Take a class name, make a Class object

Create object of that class, cast and use it

Statically convert

Class.newInstance new T()

1. String className = ...;

2. Class c = Class.forName(className);

3. Object o = c.newInstance();

4. T t = (T) o;

new T1();

new T2();

...

12

Reflection API

Package java.lang.reflect

Field class

get name and access for an arbitrary field

Method class

get info about an arbitrary method (and invoke it)

Constructor class

get info about an arbitrary constructor (and invoke it)

Class class

creates new instances of Field, Method, and Constructor

Array class

static methods to create and get info about arbitrary arrays

…..

With the exception of

java.lang.reflect.ReflectPermission, n

one of the classes in java.lang.reflect

have public constructors.

java.lang.Class

For every type of object, the Java virtual machine

instantiates an immutable instance of java.lang.Class

Class objects represent a loaded class

Provides methods to examine the runtime properties of the

object

its methods

its fields

its superclass

the interfaces it implements

whether it's an array

Provides the ability to create new classes and objects.

Entry point for all of the Reflection APIs

14

Obtaining a Class Object

To get to these classes, it is necessary to invoke

appropriate methods on Class.

1. At compile time, using the symbolic class name:

Class c1 = String.class;

Class c2 = Employee[].class;

2. At runtime, by calling getClass( ) on any object:

Class c3 = obj.getClass( );

3. At runtime, by passing a class name (string) to the

forName( ) static method:Class c = Class.forName( "java.util.Date" );

Retrieving Class Objects - Examples

Object.getClass()

the simplest way to get its Class is to invoke Object.getClass()

Class c = "foo".getClass();

Returns the Class for String

Class c = System.console().getClass();

the Class corresponding to java.io.Console.

enum E { A, B }; Class c = A.getClass();

A is is an instance of the enum E; thus getClass()

returns the Class corresponding to the enumeration type

E.

byte[] bytes = new byte[1024]; Class c = bytes.getClass();

Since arrays are Objects, it is also possible to invoke

getClass() on an instance of an array. The returned Class

corresponds to an array with component type byte.

Retrieving Class Objects - Examples

The .class Syntax

If the type is available but there is no instance then it is

possible to obtain a Class by appending ".class" to the

name of the type.

This is also the easiest way to obtain the Class for a

primitive type.

boolean b;

Class c = b.getClass(); // compile-time error

Class c = boolean.class; // correct

Class c = java.io.PrintStream.class;

Class c = int[ ][ ][ ].class;

Retrieving Class Objects - Examples Class.forName() If the fully-qualified name of a class is available, it is possible to get

the corresponding Class using the static method Class.forName() Class driverObject = Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver");

Class c = Class.forName("com.duke.MyLocaleServiceProvider")

TYPE Field for Primitive Type Wrappers Two ways

1. .class syntax, more convenient and the preferred way

Class c = boolean.class;

Class c1 = String.class;

Class c2 = Employee[].class;

2. All primitive types & void has a wrapper class in java.lang, used for boxing of primitive types to reference types.

Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.

Class c = Double.TYPE;

18

Class Methods(1 of 4)

public String getName( );

Returns the name of the class referred to by the Class object.

public boolean isInterface( );

Returns true if the Class object refers to an interface.

public boolean isArray( );

Returns true if the Class object refers to an array type.

public Class getSuperclass( );

Returns the superclass of the current Class object.

19

Class Methods (2 of 4)

public Class[] getInterfaces( );

Returns array of interface classes implemented by this class.

public Class[] getClasses( );

Returns array of inner classes within this class.

public Object newInstance( );

Creates and returns an instance of this class.

public static Class forName( String name );

Returns a Class object corresponding to a class name (static method)

20

Class Methods (3 of 4)

public Constructor[] getConstructors( );

Returns an array of all public constructors in the current class.

(import java.lang.reflect.Constructor)

public Method[] getDeclaredMethods( );

Returns an array of all public and private methods declared in the current class or interface.

(import java.lang.reflect.Method)

public Method[] getMethods( );

Returns an array of all public methods in the current class, as well as those in all superclasses and superinterfaces.

Code Examples

ReflectMethod.java & ReflectMethod2.java

Class, Parent Class, Package name

Show all methods name, signatures – use getMethods()

Bypassing Abstraction

SpecificMethodInfoDemo.java

Showing method directly using getMethod()

Bridge method Concept

SampleInvoke .java, RunMethod.java & InovkeMain.java

How to execute a method – using Method.invoke()

Recursion through Reflection

PrivateMethod.java

Executing private methods of a class

22

Member Interface

Implemented by Constructor, Method, and Field

Class getDeclaringClass( )

returns the Class object representing the class or

interface that declares the member or constructor

represented by this Member.

int getModifiers( )

returns the Java language modifiers for the member or

constructor represented by this Member, as an integer.

String getName( )

returns the simple name of the underlying member or

constructor represented by this Member.

23

Using a Method Object

Using a Method object, you can...

get its name and parameter list and

invoke the method

Obtain a Method from a signature, or get a list of all

methods.

To specify the signature, create an array of Class

objects representing the method’s parameter types.

Array will be zero-length if no parameters

Special Class objects for primitives

24

Representing the Primitive Types

Special Class objects representing the eight primitive

types:

Byte.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE,

Short.TYPE, Double.TYPE, Float.TYPE, Boolean.TYPE

Void Class type:

Void.TYPE

Also Class types for arrays, such as ...

class type for int[ ] is Integer.TYPE[].class

class type for int[ ][ ] is Integer.TYPE[][].class

25

Method Class

public class Method implements Member

{

public Class getReturnType( );

public Class[] getParameterTypes( );

public String getName( );

public int getModifiers( );

public Class[] getExceptionTypes( );

public Object invoke( Object obj, Object[] args);

}

The modifiers are stored as a bit pattern; class

Modifier has methods to interpret the bits.

26

Method Examples

Retrieve the name of a method:Method meth = c1.getDeclaredMethods( );

String name = meth.getName( );

Retrieve an array of parameter types:Class parms[] = meth.getParameterTypes( );

Retrieve a method's return type:Class retType = meth.getReturnType( );

27

Method.invoke( )

public Object invoke(Object obj, Object[] args)

If the parameters or return types are primitives, they are wrapped using one of the eight wrapper classes. example: Integer.TYPE

The first parameter to invoke is the controlling object (use null for static methods)

The second parameter is the parameter list array of objects

Disadvantages to using invoke( ): executes more slowly than static invocation

you have to handle all checked exceptions

you lose lots of compile-time checks

28

Exceptions and Invoke( )

If invoked method throws an exception, invoke( ) will

throw an InvocationTargetException

get the actual exception by calling getException

Lots of other exceptions to worry about before you

call invoke:

Did class load? ClassNotFoundException

Was method found? NoSuchMethodException

Can you access method? IllegalAccessException

29

Example: Invoking main( )

Class cl = Class.forName( className );

Class[] paramTypes = new Class[] { String[].class };

Method m = cl.getDeclaredMethod( "main", paramTypes );

Object[] args = new Object[] { new String[] { "Breathing", "Fire" } }

m.invoke( null, args );

Calling: main( String[] args )

Simplified, with no error checking:

30

Invoking a Constructor

Class c1 = Class.forName("Villain");

Class[] paramTypes = new Class[] {String.class,Integer.TYPE };

Constructor m = c1.getConstructor( paramTypes );

Object[] arguments = new Object[] { "Darth Vader", new Integer(20) };

Villan v = (Villan) m.newInstance(arguments);

Call getConstructor( ),

then call newInstance( )

catch InstantiationException

31

Member Interface

Implemented by Constructor, Method, and Field

Class getDeclaringClass( )

returns the Class object representing the class or

interface that declares the member or constructor

represented by this Member.

int getModifiers( )

returns the Java language modifiers for the member or

constructor represented by this Member, as an integer.

String getName( )

returns the simple name of the underlying member or

constructor represented by this Member.

Code Examples

ReflectMethod.java & ReflectMethod2.java Class, Parent Class, Package name

Show all methods name, signatures – use getMethods()

Bypassing Abstraction

SpecificMethodInfoDemo.java Showing method directly using getMethod()

Bridge method Concept

SampleInvoke .java, RunMethod.java & InovkeMain.java How to execute a method – using Method.invoke()

Recursion through Reflection

PrivateMethod.java

Executing private methods of a class

33

The Array Class

public class Array {

// all static methods:

public int getLength( Object arr );

public Object newInstance( Class elements, int length );

public Object get( Object arr, int index );

public void set( Object arr, int index, Object val );

// Various specialized versions, such as...

public int getInt( Object arr, int index );

public void setInt( Object arr, int index, int val );

}

import java.lang.reflect.Array;

34

Array Samples

Canine[] kennel = new Canine[10];

.

int n = Array.getLength( kennel );

// set the contents of an array element

Array.set( kennel, (n-1), new Canine( "Spaniel" ) );

// get an object from the array, determine its class,

// and display its value:

Object obj = Array.get( kennel, (n-1) );

Class c1 = obj.getClass( );

System.out.println( c1.getName( )

+ "-->"

+ obj.toString( ) );

35

Two Ways to Declare an Array

// first:

Canine kennel = new Canine[10];

// second:

Class c1 = Class.forName( "Canine" );

Canine kennel = (Canine[]) Array.newInstance( c1, 10 );

36

Example: Expanding an Array

Problem statement: write a function that receives an

arbitrary array, allocates storage for twice the size of

the array, copies the data to the new array, and

returns the new array

37

Example: Expanding an Array

Why won't this code work?

public static Object[] doubleArrayBad( Object[] arr ){

int newSize = arr.length * 2 + 1;

Object[] newArray = new Object[ newSize ];

for( int i = 0; i < arr.length; i++ )

newArray[ i ] = arr[ i ];

return newArray;

}

38

Example: Expanding an Array

Ans: This method always returns an array of Object, rather than the type of the array being copied.

public static Object[] doubleArrayBad( Object[] arr ){

int newSize = arr.length * 2 + 1;

Object[] newArray = new Object[ newSize ];

for( int i = 0; i < arr.length; i++ )

newArray[ i ] = arr[ i ];

return newArray;

}

39

Example: Expanding an Array

Use reflection to get the array type:

public Object[] doubleArray( Object[] arr )

{

Class c1 = arr.getClass( );

if( !c1.isArray( ) ) return null;

int oldSize = Array.getLength( arr );

int newSize = oldSize * 2 + 1;

Object[] newArray = (Object[]) Array.newInstance(

c1.getComponentType( ), newSize );

for( int i = 0; i < arr.length; i++ )

newArray[ i ] = arr[ i ];

return newArray;

}

see ReflectionArrayTestjava

Assignment 02

Extension One to Assignment 01

Send a class object from one machine to another

machine

On recipient side through reflection show complete

description of object

Class, Parent class, Package, interface implemented

Class Properties, their access modifier, datatype, name &

value

Class methods, list all methods, access modifiers, static/non

static, return Type, Name of method, Input parameters,

exceptions

And execute any static method object on the recipient side.

Save this assignment code as different version.

Next Lecture

Java Logging - Log4J

top related